Count Generic Method

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

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.

Namespace: System.Linq
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.Int32

A number that represents how many elements in the sequence satisfy the condition in the predicate function.

ExceptionCondition
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.
*/


Windows CE, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP SP2, Windows Vista

The .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.5

.NET Compact Framework

Supported in: 3.5

Reference

Enumerable Type
System.Linq Namespace
Show:
© 2015 Microsoft