LongCount<TSource>
System.Linq
Returns the number of elements in a sequence as a
long
.
Syntax
public static long LongCount<TSource>(this IEnumerable<TSource> source);
public static long LongCount<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
Parameters
Name | Description |
---|---|
source |
An IEnumerable<TSource> whose elements will be counted. |
predicate |
A function to test each element for a condition. |
Return Value
Type | Description |
---|---|
long |
The number of elements in the sequence or the number of elements in the sequence that satisfy the predicate. |
Exceptions
Exception Type | Condition |
---|---|
ArgumentNullException |
source is null. |
Examples
Basic Usage
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 };
// Count all elements
long count = numbers.LongCount();
Console.WriteLine($"Total elements: {count}"); // Output: Total elements: 100
// Count elements greater than 50
long countGreaterThan50 = numbers.LongCount(n => n > 50);
Console.WriteLine($"Elements greater than 50: {countGreaterThan50}"); // Output: Elements greater than 50: 50
}
}
With a Large Collection
using System;
using System.Collections.Generic;
using System.Linq;
public class ExampleLargeCollection
{
public static void Main(string[] args)
{
// Imagine a collection with more than Int32.MaxValue elements
// For demonstration purposes, we simulate a large count
IEnumerable<string> veryLargeSequence = Enumerable.Range(0, 2_500_000_000).Select(i => i.ToString());
// Using LongCount() is essential here to avoid overflow
long totalCount = veryLargeSequence.LongCount();
Console.WriteLine($"The number of elements in the very large sequence is: {totalCount}");
}
}
The
LongCount()
method is particularly useful when dealing with sequences that might contain a number of elements exceeding Int32.MaxValue
(approximately 2 billion). The standard Count()
method returns an int
, which would overflow in such cases.
Remarks
The LongCount()
method iterates through the sequence to count the elements. If the sequence is ordered, the LongCount()
method can use information about the ordering to return the count more efficiently.
If the sequence has more than Int32.MaxValue
elements, using Count()
would result in an overflow exception. LongCount()
returns a long
, which can accommodate a much larger number of elements.