leora leora - 1 year ago 91
C# Question

how to check if object already exists in a list

I have a list

List<MyObject> myList


and i am adding items to a list and i want to check if that object is already in the list.

so before i do this:

myList.Add(nextObject);


i want to see if nextObject is already in the list.

the object "MyObject" has a number of properties but comparison is based on matching on two properties.

what is the best way to do a check before i add a new "MyObject" to thsi list of "MyObject"s

the only solution i thought up was to change from a list to a dictionary and them make the key a concatenated string of the properties (this seems a little unelegant)

any other cleaner solutions using list or LINQ or something else?

Answer Source

It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:

  1. The list is relatively stable (not a lot of inserts/deletions, which dictionaries are not optimized for)
  2. The list is quite large (otherwise the overhead of the dictionary is pointless).

If the above are not true for your situation, just use Any():

Item wonderIfItsPresent = ...
bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);'

This will enumerate through the list until it finds a match, or until it reaches the end.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download