2017-12-27 81 views
-1

所以我制作了一副带有枚举的卡片组。但现在我需要通过List<T>删除不同套装中从2到6的所有卡片。这段代码被给出:删除卡组中的特定卡片

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
    var d = new Deck(); 
    Log(Converteer.ToString(d), "NIEUWE DEK"); 
    // this works 

    d.RemoveNonManilleCards(); 
    Log(Converteer.ToString(d, 8), "MANILLE-DECK"); 
    // should be -> 
    // ♠A - ♠7 - ♠8 - ♠9 - ♠10 - ♠B - ♠D - ♠H 
    // ♥A - ♥7 - ♥8 - ♥9 - ♥10 - ♥B - ♥D - ♥H 
    // ♣A - ♣7 - ♣8 - ♣9 - ♣10 - ♣B - ♣D - ♣H 
    // ♦A - ♦7 - ♦8 - ♦9 - ♦10 - ♦B - ♦D - ♦H 

而这是正在创建的套牌和删除卡片的空白。但我认为我完全错了。

public partial class Deck : List<Card> 
{ 
    public Deck() 
    { 
     MakeDeck(); 
    } 
    protected virtual void MakeDeck() 
    { 
     foreach (Suit k in System.Enum.GetValues(typeof(Suit))) 
     { 
      foreach (Rank n in System.Enum.GetValues(typeof(Rank))) 
      { 
       this.Add(new Card(k, n)); 
      } 
     } 
    } 

    public void RemoveNonManilleCards() 
    { 
     foreach (Suit k in System.Enum.GetValues(typeof(Suit))) 
     { 
      foreach (Rank n in System.Enum.GetValues(typeof(Rank))) 
      { 
       this.RemoveRange(1, 5); 
      } 
     } 

    } 

你们有人能指点我吗?

+0

这可能不正确,因为我不知道你的枚举是怎么样的,但你为什么不使用LINQ来删除所有值为2到6的卡? 'this.Where(card => c.Rank> 6 && c.Rank <1);' –

+0

对于RemoveRange在foreach中没有意义(排名 – Paparazzi

+2

这不是一个答案,所以发表评论。实践中,当通过索引(本例中为List)从集合中移除时,最好是向后迭代集合,这样可以防止集合被“折叠”,并且刚刚移除的索引被再次填充以用于下一次迭代 –

回答

0

我想我找到了如何解决这个问题

public void RemoveNonManilleCards() 
{ 
    for (int index = Count - 1; index >= 0; --index) 
    { 
    Kaart kaart = this[index]; 
    if (card.rank>= Rank.Two&& card.Rank<= Rank.Zes) 
     this.RemoveAt(index); 
    } 

感谢您的答案!