2016-04-23 61 views
1

的所有元素的值我是新来的,我想一些帮助列表...获取列表<x, y>

其实,我想我的List<x, y>一个变量的每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(“索引超出范围。必须小于集合的大小 非负少“)

+1

在for循环中,应将<=更改为<,因为它只有Count元素。 – hazjack

+1

如果一件物品的“Qt”是3或更多,你确定只想增加'nbCards' 1吗?为什么'nbCards + = 0;'行?它没有做任何有用的事情。为什么使用'Equals'来比较字节而不是'=='? –

+1

不是列表。列表 Paparazzi

回答

5

你通过你的收藏以错误的方式循环。而不是

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

它必须是

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

(你也可以去掉“这个”资格,这似乎像Java代码)

新方法:如果您只是要总结的所有卡的属性card.Qt你可以做

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

(proveded是card.Qt只有0和2之间的值,它仍然同样的逻辑 - 我让自己总结的类型更改为而不是byte。如果这样做,您还需要在文件的开始处使用using System.Linq。)

+0

这是正确的答案。我正要写这个,然后看到了这个答案。 – Arijoon

+0

谢谢,Sum作品! –