[LINQ Operators] Count

The “Count” operator counts the number of elements in a sequence. You can provide the predicate delegate instead of using the “Where” operator.

 

1. Sample Data Objects

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

 

2. “Count” operator

  • NonDeferred operator
  • Purpose: Aggregate

 

3. Prototypes

public static int Count<T>(
  this IEnumerable<T> source)

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

The “Count()” operator returns the number of elements.

 

4. Example 1 (Standard Operator)

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

int countSmith =
  emps.Where(e => e.Name.Contains("Smith")).Count();
Console.WriteLine("The number of Smiths: {0}", countSmith); // 2

 

5. Example 2 (Query Expression)

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

 

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

In the following example, you can specify the condition directly inside the “Count()” operator rather than “Where()“.

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

int countSmith =
  emps.Count(e => e.Name.Contains("Smith"));
Console.WriteLine("The number of Smiths: {0}", countSmith); // 2

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