Any is LINQ functionality to validate whether collection contains at least one element which meets given criteria.
Let’s start with example collection of integers:
1 |
var integers = new List<int>() { 36, 10, 4, 23, 1 }; |
First call the Any function without any parameter, which means we check if integers collection contains at least one element:
1 |
bool result1 = integers.Any(); |
Print a result to the console:
1 |
Console.WriteLine(result1); |
Result:
1 |
True |
As we can see the result is True because collection is not empty.
Now let’s use Any function with two different filtering criteria: first checks if collection contains items greater than 10, and second checks if collection contains items lower than 0.
1 2 3 4 5 |
bool result2 = integers.Any(x => x > 10); bool result3 = integers.Any(x => x < 0); Console.WriteLine(result2); Console.WriteLine(result3); |
Result:
1 2 |
True False |
First query returns True because there is at least one element greater than 10 (actually there are two such elements). Second query returns False because there are no items in the collection lower than 0.