Enumerable.CountBy<TSource,TKey> メソッド

定義

キーでグループ化されたソース シーケンス内の要素の数を返します。

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))

型パラメーター

TSource

sourceの要素の型。

TKey

keySelectorによって返されるキーの型。

パラメーター

source
IEnumerable<TSource>

カウントする要素を含むシーケンス。

keySelector
Func<TSource,TKey>

各要素のキーを抽出する関数。

keyComparer
IEqualityComparer<TKey>

キーを比較する IEqualityComparer<T>

返品

source内の各キーの出現頻度を含む列挙可能。

次のコード例では、 CountBy を使用して各部門の従業員数を計算する方法を示します。

(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
*/

適用対象