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
- MSDN Enumerable.Count - .NET Framework documentation
- LINQ Aggregation Methods
- LINQ Sum - gets sum of numeric collection
- LINQ Max - gets maximal item from collection
- LINQ Min - gets minimal item from collection
- LINQ Count - counts number of items in a collection (result type is Int32)
- LINQ LongCount - counts number of items in a collection (result type is Int64)
- LINQ Average - computes average value of numeric collection
- LINQ Aggregate - applies aggregate function to a collection
- C# List - illustrative examples of all List<T> methods
- C# foreach - how foreach and IEnumerable works debuggable online