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

適用於