Enumerable.CountBy<TSource,TKey> 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回按键分组的源序列中的元素计数。
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
*/