LongCount (LINQ)

Enumerable.LongCount is extension method from System.Linq namespace. It counts number of items in collection just like Enumerable.Count method, but the result type is long (Int64) instead of int (Int32).

Use this method only if there is possibility that number of items in the IEnumerable collection is greater than Int32.MaxValue (2,147,483,647). Otherwise use Enumerable.Count because it is optimized for collections which implements ICollection (lists, arrays, dictionaries). See LongCount Implementation bellow.

LongCount Examples

Counts number of items in the IEnumerable collection.

Returns 0 if there is no item in the collection.

LongCount with Predicate

Counts number of items which match specified predicate.

LongCount 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.

LongCount Implementation

This is .NET Framework implementation of Enumerable.LongCount method. Note that implementation of LongCount is more performance-intensive in some cases than implementation of Enumerable.Count. It's because Enumerable.Count implementation first checks whether the IEnumerable can be cast to ICollection (which is List, array [], Dictionary, HashSet). If so, it simply returns value of its Count property (of type int). LongCount implementation doesn't do the optimization and always simply counts the items.


See also

By Jan Slama, 17-Apr-2016
;