This C# method receives a Predicate
. It determines if a matching element exists in a collection. We could do this with a loop construct.
The Any()
extension method provides another way to check for a matching element. It has some benefits—it can reduce code size.
Add the System.Linq
using directive at the top of your program. This allows you to call the Any()
extension. In this example, we see an array of 3 integer values.
Any()
method.int
. The second tests for any int
greater than 3. The third checks for any int
equal to 2.using System; using System.Linq; int[] array = { 1, 2, 3 }; // See if any elements are divisible by two. bool b1 = array.Any(item => item % 2 == 0); // See if any elements are greater than three. bool b2 = array.Any(item => item > 3); // See if any elements are 2. bool b3 = array.Any(item => item == 2); // Write results. Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3);True False True
How does the Any()
method work? When you call the Any method, you are passing a Predicate
type, which is a function with a bool
result.
Predicate
returns true for, the true result is propagated. It uses an early-exit.The Any()
method evaluates a Predicate
method on the source collection. It returns a boolean indicating whether any element matches the Predicate
.