c# – Difference between Any, Contains and Exists

Question:

What is the difference between Any , Contains and Exists ?

What is the appropriate context for each of them? (Usage examples)

What are the advantages and disadvantages?

Answer:

TL;DR;

They all check whether an element exists in a particular collection of elements, but in different ways.

Any() came with Linq, works with any enumerable collection, and takes Func<T, bool> as a parameter. Any() also has a parameterless version that checks if the collection contains any elements, that is, if Count > 0 .

Exists() only works with List<T> and takes a Predicate<T> as a parameter – this allows two or more validations to be done. Eg lista.Exists(x => x == 1 || x == 2);

Contains() also works only with List<T> , but instead of receiving a Predicate<T> takes an element ( T ) as a parameter.


Assuming you have a list of integers

var lista = new List<int> { 1, 2, 3, 4, 5 }; 

Any()

It is an extension method of the System.Linq namespace . It came with the .NET Framework 3.5 and works with any collection that is "countable". Take Func<T, bool> as a parameter (in practice this is the same thing as taking Predicate<T> ).

E.g. of use (check if there are elements 2 or 3):

bool existe = lista.Any(x => x == 2 || x == 3);

Contains()

Default method of List<T> . Takes an element as a parameter.

E.g. of use (check if there is element 1):

bool existe = lista.Contains(1);

Exists()

It is also a standard method of List<T> . The only difference from it to Contains is that it receives a Predicate<T> as a parameter, instead of receiving an element. It exists basically so that it is not necessary to make several Contains() when you need to check the existence of more than one element in a list.

Ex. of use (check if there are elements 1 or 3):

bool exists = lista.Exists(x => x == 1 || x == 3);
Scroll to Top