What is the difference between Contains
and Any
in LINQ?
Contains
takes an object, Any
takes a predicate.
You use Contains
like this:
listOFInts.Contains(1);
and Any
like this:
listOfInts.Any(i => i == 1);
listOfInts.Any(i => i % 2 == 0); // Check if any element is an Even Number
So if you want to check for a specific condition, use Any
. If you want to check for the existence of an element, use Contains
.
MSDN for Contains, Any
Contains
Determines whether a sequence contains a specified element by using the default equality comparer.
Any
Determines whether a sequence contains any elements.
As for the documentation:
Can't seem to find to find any documentation on it.
All (most?) LINQ extension methods: here
Contains checks if the sequence contains a specified element.
Enumerable.Any checks if element of a sequence satisfies a condition.
Consider the following example:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
bool contains = list.Contains(1); //true
bool condition = list.Any(r => r > 2 && r < 5);
Another difference as mentioned here is on the performance
Contains
is O(n) for a List
and O(1) for a HashSet
Any
is simply O(n)Contains cares about whether the source collection is an ICollection
, Any does not.
Enumerable.Contains http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#f60bab4c5e27a849
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)
{
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Contains(value);
}
return source.Contains<TSource>(value, null);
}
Enumerable.Any http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#6a1af7c3d17845e3
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
foreach (TSource local in source)
{
if (predicate(local))
{
return true;
}
}
return false;
}