Enumerable.Count Method
public static int Count<TSource>(this IEnumerable<TSource> source)
public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Description
Counts the number of elements in a sequence.
There are two overloads for the Count
method:
- The first overload,
Count<TSource>(this IEnumerable<TSource> source)
, returns the total number of elements in the sequence. - The second overload,
Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
, returns the number of elements in the sequence that satisfy a condition specified by a predicate.
These methods are part of the LINQ (Language Integrated Query) library in .NET, providing powerful data manipulation capabilities.
Parameters
Count<TSource>(this IEnumerable<TSource> source)
Name | Type | Description |
---|---|---|
source |
IEnumerable<TSource> |
An IEnumerable<T> whose elements to count. |
Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
Name | Type | Description |
---|---|---|
source |
IEnumerable<TSource> |
An IEnumerable<T> whose elements to count. |
predicate |
Func<TSource, bool> |
A function to test each element for a condition. |
Returns
int
The number of elements in the input sequence or the number of elements that satisfy the predicate.
Exceptions
Exception Type | Condition |
---|---|
ArgumentNullException |
source is null. |
Examples
Example 1: Counting all elements
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 };
// Count all elements in the list
int count = numbers.Count();
Console.WriteLine($"Total number of elements: {count}"); // Output: Total number of elements: 5
}
}
Example 2: Counting elements that satisfy a condition
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 };
// Count elements that are greater than 5
int evenCount = numbers.Count(n => n % 2 == 0);
int greaterThanFiveCount = numbers.Count(n => n > 5);
Console.WriteLine($"Number of even elements: {evenCount}"); // Output: Number of even elements: 5
Console.WriteLine($"Number of elements greater than 5: {greaterThanFiveCount}"); // Output: Number of elements greater than 5: 5
}
}
Remarks
For generic types that implement ICollection<T>
, the Count
property is used for efficiency, as it provides the count in O(1) time. For other types that implement IEnumerable<T>
, the Count()
method iterates through the sequence to determine the count, which takes O(n) time.
The overload that takes a predicate can be more efficient than calling Count()
followed by a Where()
clause in some scenarios, especially for custom iterators.