【问题标题】:Get all elements value of List<x, y>获取 List<x, y> 的所有元素值
【发布时间】:2016-08-17 05:01:36
【问题描述】:

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

实际上,我想将我的List&lt;x, y&gt; 的每个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&lt;DeckEntry&gt; LstCardsWithQt

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

顺便说一句,this.LstCardsWithQt[i].Qt != 0 出现错误

ArgumentOutOfRangeExeption("索引超出范围。必须是 非负且小于集合的大小")

【问题讨论】:

  • 在for循环中,你应该把
  • 如果项目的 Qt 为 3 或更多,您确定只想将 nbCards 增加 1 吗?为什么是nbCards += 0; 行?它没有做任何有用的事情。为什么使用Equals而不是==来比较字节?
  • 不是列表。列出

标签: c# .net list loops


【解决方案1】:

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

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 at如果你这样做,你的文件的开头。)

【讨论】:

  • 这是正确答案。我正要写这个,然后看到了这个答案。
猜你喜欢
  • 2022-08-02
  • 2022-01-07
  • 2023-03-19
  • 2012-05-13
  • 1970-01-01
  • 2011-02-14
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多