Counting List Occurrences with GroupBy
A common programming task involves counting the occurrences of elements within a list. In C#, a simple solution can be achieved using a combination of GroupBy and Count.
var list = new List<int> { 1, 2, 3, 4, 5, 2, 2, 2, 4, 4, 4, 1 }; var grouped = list.GroupBy(i => i); foreach (var group in grouped) { Console.WriteLine($"{group.Key} {group.Count()}"); }
In this example, a lambda function (Func
The subsequent loop iterates through the grouped items, printing the key and the count of elements in each group. This provides a quick and efficient way to count occurrences within a list.
The above is the detailed content of How Can I Efficiently Count List Element Occurrences in C#?. For more information, please follow other related articles on the PHP Chinese website!