简体   繁体   English

从列表中删除项目

[英]remove item from a list

I have object Card 我有对象Card

public class Card {
    public int ID { get; set; }
    public string Name { get; set; }
    public Color CardColor { get; set; }
    public int Size { get; set; }
}

and I have list of Card . 而且我有Card清单。 I want to remove Card from list that has different ID but other properties are same. 我想从ID不同但其他属性相同的列表中删除Card

cardList.Remove(mycard);

is not working. 不管用。

Find the item in the list that matches, by comparing the Name (or whatever), then remove that. 通过比较名称(或其他名称)在列表中找到匹配的项目,然后将其删除。

For example: 例如:

var toRemove = cardList.SingleOrDefault(c => c.Name == mycard.Name);
if (toRemove != null) cardList.Remove(toRemove);

You should override Equals method. 您应该重写Equals方法。 Remove use Equals to evaluate if the card is the one that you want to remove. 删除使用等于评估卡是否是您要删除的卡片。 So override it in Card class with the logic to evaluate if two cards are equals. 因此在Card类中使用逻辑来覆盖它,以评估两张卡是否相等。

foreach(var card in cardList)
{
    var cardsMatching =     
        cardList.All(x=>x.Name==card.Name&&x.Color==card.Color&&x.Size==card.Size); 

    cardsMatching.Foreach(y=> {
         cardList.Remove(cardList.IndexOf(y));
    });
}

Depending on what you want to achieve, you may want to prevent cards with the same id to be inserted in the first place. 根据您要实现的目标,您可能希望首先阻止具有相同ID的卡插入。

There are two simple approaches: 有两种简单的方法:

  • Use a set with a comparer, such as: 将集合与比较器一起使用,例如:

     public class CardComparer : IEqualityComparer<Card> { public bool Equals(Card x, Card y) { return x.ID == y.ID; } public int GetHashCode(Card obj) { return obj.ID; } } var hash = new HashSet<Card>(new CardComparer()); 
  • Use dictionary with ID as a key: 使用ID为关键字的字典:

     var dict = new Dictionary<int, Card>(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM