Home
C#
Any Method
Updated Nov 29, 2023
Dot Net Perls
Any. This C# method receives a Predicate. It determines if a matching element exists in a collection. We could do this with a loop construct.
A simple method. The Any extension method provides another way to check for a matching element. It has some benefits—it can reduce code size.
Predicate
Extension
All
Example code. 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.
Here In the program, the 3 values (1, 2 and 3) determine the results of the Any method.
int Array
And The first call tests for any even int. The second tests for any int greater than 3. The third checks for any int equal to 2.
Odd, Even
Tip You can change the expressions in the lambda to determine the correctness of the tests.
Lambda
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
Internals. 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.
And Internally, the Any method loops through each element in the source collection.
Then When it finds an element that the 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.
LINQ
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 29, 2023 (edit link).
Home
Changes
© 2007-2025 Sam Allen