[LINQ Operators] All

The “All” operator checks whether all elements of a sequence satisfy 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. “All” operator

  • NonDeferred operator
  • Purpose: Quantifier

 

3. Prototypes

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

The “All()” operator returns “true” if all elements in the source sequence matches the condition.

 

4. Example 1 (Standard Operator)

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

bool isAllSmith =
  emps.All(e => e.Name.Contains("Smith"));

if (isAllSmith)
  Console.WriteLine("Everyone is Smith");
else
  Console.WriteLine("Not everyone is Smith");

 

5. Example 2 (Query Expression)

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

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

bool isAllSmith =
  (from e in emps
   where e.Name.Contains("Mark") // Mark Smith
   select e)
  .All(e => e.Name.Contains("Smith"));

if (isAllSmith)
  Console.WriteLine("Everyone is Smith");
else
  Console.WriteLine("Not everyone is Smith");

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