Count Generic Method
The title of generic type and method topics currently reflects Visual Basic syntax. In C# syntax, <T> replaces (Of T). This is by design for this pre-release.
Returns a number that represents how many elements in the specified sequence satisfy a condition.
Assembly: System.Core (in System.Core.dll)
public static int Count<TSource> ( IEnumerable<TSource> source, Func<TSource, bool> predicate )
Not applicable.
Type Parameters
- TSource
The type of the elements of source.
Parameters
- source
- System.Collections.Generic.IEnumerable<(Of T>)
An IEnumerable<(Of T>) that contains the elements to be counted.
- predicate
- System.Linq.Func<(Of TArg0, TResult>)
A function to test each element for a condition.
Return Value
System.Int32A number that represents how many elements in the sequence satisfy the condition in the predicate function.
| Exception | Condition |
|---|---|
| ArgumentNullException | source or predicate is null. |
| OverflowException | The number of elements in source is larger than MaxValue. |
If the type of source implements ICollection<(Of T>), that implementation is used to obtain the count of elements. Otherwise, this method determines the count.
You should use the LongCount method when you expect and want to allow the result to be greater than MaxValue.
The following code example demonstrates how to use Count to count the elements in an array that satisfy a condition.
struct Pet { public string Name; public bool Vaccinated; } public static void CountEx2() { Pet[] pets = { new Pet { Name="Barley", Vaccinated=true }, new Pet { Name="Boots", Vaccinated=false }, new Pet { Name="Whiskers", Vaccinated=false } }; int numberUnvaccinated = pets.Count(p => p.Vaccinated == false); Console.WriteLine("There are {0} unvaccinated animals.", numberUnvaccinated); } /* This code produces the following output: There are 2 unvaccinated animals. */