Difference between Any, Contains and Exists

Asked

Viewed 11,209 times

22

What’s 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?

3 answers

23


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 gets Func<T, bool> as a parameter. O Any() also has a version without any parameter that checks if the collection contains any element, ie if Count > 0.

Exists() works only with List<T> and receives a Predicate<T> as a 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 a Predicate<T> 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()

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

Ex. for use (check for items 2 or 3):

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

Contains()

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

E.g. for use (check for element 1):

bool existe = lista.Contains(1);

Exists()

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

E.g. for use (check for items 1 or 3):

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

15

Any() - Determines if any, any, element of a enumerable collection meets a specified condition.

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

Contains() - It’s a special case of Any(), instead of establishing a parameterized condition it already has a defined condition, it 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 can perform better in some types of collection, if this limitation suits it. It has an obviously simpler syntax.

lista.Contains(1)

Exists() - It’s the same as the Any() but existed before LINQ was invented for a List, not for others enumerable. In general it should be avoided.

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

All examples are equivalent. Obviously other examples may be unfeasible in the three options.

12

Exists is a class method (I think List) that checks whether an element is present in that list, and has been present since . NET 2.0. It was created to be used with delegate, But it works with Ambergris. Only works with lists, and should be (more not sure) more optimized than the others (by being more specific, but I may be talking nonsense).

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

Any came with . NET 3.5 and was created to use with LINQ. It is a Extension method that works with any IEnumerable (basically, any Collection, including the 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 a IEqualityComparer to make the comparison (rather than a lambda). I find it 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());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.