Home >Backend Development >C++ >How Can I Efficiently Count List Element Occurrences in C#?

How Can I Efficiently Count List Element Occurrences in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-04 11:02:35419browse

How Can I Efficiently Count List Element Occurrences in C#?

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 ) is used to extract the grouping key, which is the element itself. The GroupBy method then groups the elements based on the key and returns an IGrouping object, where each group consists of elements with the same key.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn