[LINQ Operators] Any

The “Any” operator checks whether any element of a sequence satisfies a condition. It returns a boolean value (true/false).

 

1. Sample Data Objects

To test examples, you need to include the <data classes> in your project.

 

2. “Any” operator

  • NonDeferred operator
  • Purpose: Quantifier

 

3. Prototypes

public static bool Any<T>(
  this IEnumerable<T> source)

public static bool Any<T>(
  this IEnumerable<T> source,
  Func<T, bool> predicate)

The “Any()” operator returns “true” if the source sequence contains any element. The second syntax returns true if at least one element matches the condition.

 

4. Example 1 (Standard Operator)

IEnumerable<Employee> emps = Employee.GetEmployees();

bool isAnySmith =
  emps.Where(e => e.Name.Contains("Smith")).Any();
if (isAnySmith)
  Console.WriteLine("At least one Smith");
else
  Console.WriteLine("There's no Smith");

bool isAnyPaul =
  emps.Where(e => e.Name.Contains("Paul")).Any();
if (isAnyPaul)
  Console.WriteLine("At least one Paul");
else
  Console.WriteLine("There's no Paul");

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Any()” operator.

 

6. Example 3 (Standard Operator) – with a condition

IEnumerable<Employee> emps = Employee.GetEmployees();

bool isAnySmith =
  emps.Any(e => e.Name.Contains("Smith"));
if (isAnySmith)
  Console.WriteLine("At least one Smith");
else
  Console.WriteLine("There's no Smith");

bool isAnyPaul =
  emps.Any(e => e.Name.Contains("Paul"));
if (isAnyPaul)
  Console.WriteLine("At least one Paul");
else
  Console.WriteLine("There's no Paul");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s