Darshana
Darshana

Reputation: 2548

remove item from a list

I have object 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. I want to remove Card from list that has different ID but other properties are same.

cardList.Remove(mycard);

is not working.

Upvotes: 0

Views: 125

Answers (4)

ya23
ya23

Reputation: 14496

Depending on what you want to achieve, you may want to prevent cards with the same id to be inserted in the first place.

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:

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

Upvotes: 0

Jon Egerton
Jon Egerton

Reputation: 41549

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);

Upvotes: 2

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));
    });
}

Upvotes: 0

ema
ema

Reputation: 5773

You should override Equals method. 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.

Upvotes: 0

Related Questions