What is the difference between Contains and Any in LINQ?
What is the difference between Contains
and Any
in LINQ?
Solution 1:
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
Solution 2:
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);
Solution 3:
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;
}
Solution 4:
Another difference as mentioned here is on the performance
-
Contains
is O(n) for aList
and O(1) for aHashSet
-
Any
is simply O(n)