Home >Backend Development >C++ >How Can I Efficiently Count the Occurrences of Each Element in a C# List?
Identifying the frequency of occurrences within a list can be a valuable operation in programming. This question explores a simple method to count the occurrences of each element in a list in C#.
The proposed solution utilizes the GroupBy method, which partitions the list into distinct groups based on a specified key selector. In this case, the key selector is a lambda expression that retrieves the element itself.
The result is an IGrouping
Here's a revised version of the code snippet provided:
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() ); }
This code will produce output similar to:
1 (2) 2 (3) 3 (1) 4 (3) 5 (1)
which lists the distinct elements of the original list along with their respective counts. This method provides a concise and efficient way to perform occurrence counting within a list in C#.
The above is the detailed content of How Can I Efficiently Count the Occurrences of Each Element in a C# List?. For more information, please follow other related articles on the PHP Chinese website!