C# – How to check if an item exists in a list

In this article we’ll present and compare two functions which offer us a possibility to check whether an item exists in a given list. These functions are Exists and Contains, both available in System.Collections.Generic namespace. Provided examples are for two different lists: one containing integers and other one containing objects of custom created class.

List of integers

For the purpose of this article, let’s create an example list containing few integers.

Exists method

Exists function receives a predicate as an argument and returns bool representing the result of given formula. Predicate can be either simple comparison of two objects or really complicated equation. Returned value is true when list contains at least one item which meets defined criteria. No matter if one item is matched or multiple, the result will be the same.

Contains method

Contains behavior is similar to Exists, however instead of a predicate, it receives an argument which is actual value to be checked. The result type is the same, which is a bool indicating whether given item is in the list or not.

List of custom objects

Now, let’s create a class which will be used to present examples of usage Exists and Contains with custom defined objects.

Having a class, we can create a list of Person objects and populate it with few entities.

Exists method

The usage of Exists function is very similar as in list with integers. It’s required to provide a predicate which will be executed against items list to verify whether any item is matched. Again, predicate might be simple or extended formula.

Contains method

Contains method expects a Person object to be passed as a parameter.

Below we’ve created an object p1 where forename is Laura and surname is Jones. Even though such person exists on a list, we still get result r4 = false. It’s because the object we passed is not exactly the same instance as the one added to the list.

Another object, p2 is assigned as a second item from the list. This time Contains method returns true, because that object’s instance actually exists on the list.

If we’d like to change the way how objects are compared, we can easily do it by implementing IEquatable interface and defining our custom Equal function.

If we run below code again, this time we get both results as true. Having custom comparer function, we don’t care anymore whether two objects are exactly the same instances. Now objects are considered to be the same if both forenames and surnames are equal.