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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With