I-edit

Enumerable.CountBy<TSource,TKey> Method

Definition

Returns the count of elements in the source sequence grouped by key.

public static System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,int>> CountBy<TSource,TKey>(this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,TKey> keySelector, System.Collections.Generic.IEqualityComparer<TKey>? keyComparer = default);
static member CountBy : seq<'Source> * Func<'Source, 'Key> * System.Collections.Generic.IEqualityComparer<'Key> -> seq<System.Collections.Generic.KeyValuePair<'Key, int>>
<Extension()>
Public Function CountBy(Of TSource, TKey) (source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey), Optional keyComparer As IEqualityComparer(Of TKey) = Nothing) As IEnumerable(Of KeyValuePair(Of TKey, Integer))

Type Parameters

TSource

The type of elements of source.

TKey

The type of the key returned by keySelector.

Parameters

source
IEnumerable<TSource>

A sequence that contains elements to be counted.

keySelector
Func<TSource,TKey>

A function to extract the key for each element.

keyComparer
IEqualityComparer<TKey>

An IEqualityComparer<T> to compare keys with.

Returns

An enumerable containing the frequencies of each key occurrence in source.

Examples

The following code example demonstrates how to use CountBy to calculate the number of employees in each department.

(string Name, int Age, string Department)[] employees =
{
    ("Saly", 23, "IT"),
    ("David", 25, "Sales"),
    ("Mahmoud", 22, "IT"),
    ("Qamar", 22, "HR"),
    ("Sara", 25, "IT"),
    ("John", 26, "HR"),
    ("Jaffar", 32, "Sales")
};

// Count the number of employees per department
var countPerDepartment = employees.CountBy(employee => employee.Department);

foreach (var item in countPerDepartment)
{
    Console.WriteLine($"Department: {item.Key} - Employees Count: {item.Value}");
}

/*
This code produces the following output:

Department: IT - Employees Count: 3
Department: Sales - Employees Count: 2
Department: HR - Employees Count: 2
*/

Applies to