14

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?

Kohnarik
  • 377
  • 2
  • 5
  • 19

4 Answers4

21

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

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • Beat me to it! This is how you would do it Kohnarik – Ben Clarke Jan 14 '16 at 14:00
  • 2
    Thanks, I love you. have my babies – Kohnarik Jan 14 '16 at 14:00
  • Uhh, one more question. If I now find a nemesis with the same Dex_ID, how do I access the found nemesis? Let's act like "n" is the found nemesis. example: `...else { n.Dex_ID = n.Dex_ID + nemesis.Dex_ID }` – Kohnarik Jan 14 '16 at 14:32
  • 2
    Use `FirstOrDefault` read about it, it should be like: `var item = NemesisList.FirstOrDefault(n=> n.Dex_ID == nemesis.Dex_ID);` and then modify your check like `if(item == null) {//not found } else {//found, work with item.Dex_ID....}` – Habib Jan 14 '16 at 14:37
  • I think `Single()` is way more idiomatic here. `OrDefault` is wrong imo, since we KNOW the item is in the list, if it isn't we know we have a bug, so we want to fail fast. I still think a dictionary is better here though. – sara Jan 14 '16 at 16:35
2

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)) // ...
sara
  • 3,521
  • 14
  • 34
0

Linq is your friend here:

if (!myList.Any(x => x.Dex_ID == nemesis.Dex_ID)) myList.Add(nemesis)
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

Try to use the following LINQ:

var exists = NemesisList.Any(n=>n.Dex_Id==id)
ehh
  • 3,412
  • 7
  • 43
  • 91