Enumerable.CountBy<TSource,TKey> Metode
Definisi
Penting
Beberapa informasi terkait produk prarilis yang dapat diubah secara signifikan sebelum dirilis. Microsoft tidak memberikan jaminan, tersirat maupun tersurat, sehubungan dengan informasi yang diberikan di sini.
Mengembalikan jumlah elemen dalam urutan sumber yang dikelompokkan menurut kunci.
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))
Jenis parameter
- TSource
Jenis elemen .source
- TKey
Jenis kunci yang dikembalikan oleh keySelector.
Parameter
- source
- IEnumerable<TSource>
Urutan yang berisi elemen yang akan dihitung.
- keySelector
- Func<TSource,TKey>
Fungsi untuk mengekstrak kunci untuk setiap elemen.
- keyComparer
- IEqualityComparer<TKey>
Untuk IEqualityComparer<T> membandingkan kunci dengan.
Mengembalikan
Enumerable yang berisi frekuensi setiap kemunculan kunci di source.
Contoh
Contoh kode berikut menunjukkan cara menggunakan CountBy untuk menghitung jumlah karyawan di setiap departemen.
(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
*/