C# Examples

Menu:


C# LINQ Aggregation Methods

Count (LINQ)

Enumerable.Count is extension method from System.Linq namespace. It counts number of items in collection.

Count Examples

Counts number of items in the IEnumerable collection.

Returns 0 if there is no item in the collection.

Count with Predicate

Counts number of items which match specified predicate.

Count with Query Syntax

LINQ query expression to count number of all items in the collection.

LINQ query expression to count number of items which match specified predicate.

Count with Group By

This example shows how to count number of items per group. Lets count players in each team.

Count Implementation

This is .NET Framework implementation of Enumerable.Count method. Note that there is optimization. Before counting items one by one, it first checks whether the IEnumerable<T> can be cast to ICollection<T> or ICollection. If so, it simply returns value of its Count property. ICollection<T> is implemented by List<T>, Dictionary<T>, HashSet<T>, array T[] and others.


See also

  • C# List - illustrative examples of all List<T> methods
  • C# foreach - how foreach and IEnumerable works debuggable online
By Jan Slama, 27-Mar-2016