c# - 获取 List<x, y> 的所有元素值

标签 c# .net list loops

我是新来的,我需要一些关于 List 的帮助......

实际上,我想添加每个y我的元素List<x, y>到一个变量。我知道,这可能很容易,但我仍然停留在那个部分..

/// <summary>
/// Number of cards in the deck
/// </summary>
public byte NbTotalCards
{
    get
    {
        byte nbCards = 0;

        for (byte i = 0; i <= this.LstCardsWithQt.Count; i++)
        {
            if (this.LstCardsWithQt[i].Qt != 0)
            {
                if(this.LstCardsWithQt[i].Qt.Equals(2))
                    nbCards += 2;
                else
                {
                    nbCards += 1;
                }
            }
            else
            {
                nbCards += 0;
            }
        }
        return nbCardss;
    }
}

在哪里

public List<DeckEntry> LstCardsWithQt

public DeckEntry(Card card, byte qt)
{
    this.Card = carte;
    this.Qt = qt;
}

顺便说一句,我在 this.LstCardsWithQt[i].Qt != 0 上遇到错误

ArgumentOutOfRangeExeption("Index was out of range. Must be non-negative and less than the size of the collection")

最佳答案

您正在以错误的方式循环浏览您的收藏。而不是

for (byte i = 0; i <= this.LstCardsWithQt.Count; i++)

必须是

for (byte i = 0; i < this.LstCardsWithQt.Count; i++)

(您也可以删除“this”限定符,这看起来像 Java 代码)

新方法:如果你只想总结所有卡片的属性card.Qt,你可以这样做

public int NbTotalCards
{
    get
    { 
         return LstCardsWithQt.Sum( card => card.Qt);
    }
}

(证明 card.Qt 只有 0 到 2 之间的值,并且它仍然是相同的逻辑 - 我允许自己将 sum 的类型更改为 int 而不是byte。如果这样做,您还需要在文件开头使用 using System.Linq。)

关于c# - 获取 List<x, y> 的所有元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36812880/

相关文章:

c# - 警告 : Can't find dll

c# - 如何自动初始化一个数字递增的列表?

c# - 服务引用不会为 DateTime 创建 'specified' 属性

c# - 使用 .NET Reflector 的示例

.net - 在 GetKeyboardType() Windows API 调用中 Delphi 6 程序启动期间发生访问冲突

Python:仅在列表末尾删除重复值

python - 尝试将一个列表拆分为主列表内的多个列表 - Python

python - 用 Python 解析 XML 文件并在每个列表元素中获取字母 'u'

c# - Bing map 控件挂起后退导航

c# - 从 OData 返回单个实体 - .Net