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 this list of "MyObject"s.

The only solution I thought up was to change from a list to a dictionary and then 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?


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 the method 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.


Simply use Contains method. Note that it works based on the equality function Equals

bool alreadyExist = list.Contains(item);

If it's maintainable to use those 2 properties, you could:

bool alreadyExists = myList.Any(x=> x.Foo=="ooo" && x.Bar == "bat");