Difference between Any, Contains and Exists

17

What is the difference between Any , Contains and Exists ?

What is the appropriate context for each of them? (Examples of use)

What are the advantages and disadvantages?

    
asked by anonymous 10.12.2015 / 13:29

3 answers

18

TL; DR;

They all do the same thing - check if an element exists in a given collection of elements - in different ways.

Any() came with Linq, works with any enumerable collection, and gets Func<T, bool> as a parameter. The Any() also has a version without any parameter that checks if the collection contains some element, ie, Count > 0 .

Exists() works only with List<T> and gets Predicate<T> as parameter - this allows two or more validations to be made. Ex: lista.Exists(x => x == 1 || x == 2);

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

Assuming you have a list of integers

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

Any()

This is a method of extending the namespace System.Linq . It came with the .NET Framework 3.5 and works with any collection that is "enumerable." It receives Func<T, bool> as a parameter (in practice it is the same as receiving Predicate<T> ).

Ex. of use (check for elements 2 or 3):

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

Contains()

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

Ex. of use (check if element 1 exists):

bool exists = lista.Contains(1);

Exists()

It is also a default method of List<T> . The only difference from it to Contains is that it gets Predicate<T> as a parameter, instead of receiving an element. It basically exists so you do not need to do multiple Contains() when you need to check for more than one element in a list.

Ex. of use (check for elements 1 or 3):

bool exists = lista.Exists(x => x == 1 || x == 3);
    
10.12.2015 / 13:44
13

Any - Determines whether any elements in an enumerable collection meets a specified condition.

lista.Any(x => x == 1)

Contains - This is a special case of Any , instead of establishing a condition, it already takes the element and makes an equality comparison to know if there is an element in the list that has that value (note that the parameter is not a predicate, it will not receive a lambda but an object). It may perform better on some types of collection if this limitation meets it. It has an obviously simpler syntax.

lista.Contains(1)

Exists - It's the same as Any but it existed before LINQ was invented for a List , not for other enumerable ones. In general it should be avoided.

lista.Exists(x => x == 1)

All examples are equivalent. Obviously other examples may be impractical in all three options.

    
10.12.2015 / 13:35
10

Exists is a method of a class (I think List ) that checks if an element is present in that list, and is present since .NET 2.0. It was designed to be used with delegate , but works with lambdas. It only works with lists, and should be (more I'm not sure) more optimized than the others (to be more specific, but I can be talking bullshit).

minhaLista.Exists(x => x.Contains("abc"));

Any came with .NET 3.5 and was designed for use with LINQ. It is an extension method that works with any IEnumerable (basically any Collection , including any classes you create that implement IEnumerable ).

meuEnumerable.Any(); // Tem algum elemento?
meuEnumerable.Any(x => x.Contains("abc")); // Tem algum elemento com "abc"?

Contains has the same characteristics as Any (.NET 3.5, LINQ), but you use IEqualityComparer to make the comparison (instead of a lambda). I find this useful when you have to make the same comparison in several places.

// Vou utilizar essa comparação parcial em vários lugares. Para
// evitar escrever o lambda do exemplo anterior em todo lugar,
// uso isso. Facilita refatorar, evita duplicação.
// Especialmente útil para comparações mais complexas
class PartialEqualityComparer : IEqualityComparer<String> {

    public bool Equals(String x, String y) {
        return x.Contains(y);
    }

    // GetHashCode...
}

meuEnumerable.Contains("abc", new PartialEqualityComparer());
    
10.12.2015 / 13:55