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
Release: 2025-01-04 11:02:35
Original
400 people have browsed it

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()}");
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template