Home >Backend Development >C++ >How to Count List Element Occurrences and Add Counts Back to the List in C#?

How to Count List Element Occurrences and Add Counts Back to the List in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 09:07:35487browse

How to Count List Element Occurrences and Add Counts Back to the List in C#?

Counting List Occurrences in C#

This inquiry seeks a method in C# to count the frequency of each element within a list and add those counts back into the list.

Solution:

Consider the following approach, which leverages the GroupBy method:

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy(i => i);

foreach (var grp in g)
{
  Console.WriteLine("{0} {1}", grp.Key, grp.Count());
}

Explanation:

  • GroupBy takes a lambda function as an argument, which determines the key for grouping. In this case, we group by the elements themselves, resulting in an IGrouping collection.
  • Iterating through the IGrouping collection, we access each group's key (the unique element) and count using Count().

The above is the detailed content of How to Count List Element Occurrences and Add Counts Back to the List 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