Kohnarik
Kohnarik

Reputation: 377

C# Check if List contains a custom object with the same value

I have a custom object (the properties must be strings):

public class Nemesis
{
    public String Dex_ID;
    public String Value;
}

I have a certain function, which creates new instances of that object, adds values to them and then adds them to this List:

private List<Nemesis> _nemesisList;
public List<Nemesis> NemesisList
{
    get { return _nemesisList; }
    set { _nemesisList = value; }
}

Normally, I'd use this to check for existing things:

if (!NemesisList.Contains(nemesis))
{
    NemesisList.Add(nemesis);
}

But this time I want to check if my List already contains a nemesis with the same nemesis.Dex_ID. How do I do that?

Upvotes: 14

Views: 38286

Answers (4)

sara
sara

Reputation: 3609

Using LINQ:

if (!NemesisList.Any(n => n.Dex_ID == nemesis.Dex_ID)) // ...

OR

if (!NemesisList.Select(n => n.Dex_ID).Contains(nemesis.Dex_ID)) // ...

The better solution is probably to create a dictionary though. They are built for quick lookups based on some key value.

if (!NemesisDict.ContainsKey(nemesis.Dex_ID)) // ...

Upvotes: 2

Habib
Habib

Reputation: 223422

If you only want to to check against the the ID field and ignore others then you can do :

if(!NemesisList.Any(n=> n.Dex_ID == nemesis.Dex_ID))

otherwise if you want to perform comparison for all the fields then you can override Equals and GetHashCode.

See: Correct way to override Equals() and GetHashCode()

Upvotes: 22

ehh
ehh

Reputation: 3480

Try to use the following LINQ:

var exists = NemesisList.Any(n=>n.Dex_Id==id)

Upvotes: 0

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

Linq is your friend here:

if (!myList.Any(x => x.Dex_ID == nemesis.Dex_ID)) myList.Add(nemesis)

Upvotes: 0

Related Questions