Метод CountBy
Метод CountBy класса Enumerable считает элементы по ключу.
Синтаксис
IEnumerable<KeyValuePair<TKey, int>> stats = source.CountBy(x => key);
Пример
Давайте посчитаем чётность:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> nums = new List<int> {1, 2, 3, 4, 5};
foreach (var p in nums.CountBy(n => n % 2))
{
Console.WriteLine(p.Key + " " + p.Value);
}
}
}
Результат выполнения кода:
1 3
0 2