Get frequency of elements from List in C#
This post will discuss how to get the frequency of all elements from List in C#.
We can use LINQ to compute the frequency of all elements from a list. The idea is to use the Enumerable.GroupBy() method to group the elements of a sequence based on their value. A typical implementation of this approach would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int> { 2, 5, 1, 1, 2, 2, 4 }; var result = values.GroupBy(x => x); foreach (var g in result) { Console.WriteLine("{0} occurs {1} times", g.Key, g.Count()); } } } |
Output:
2 occurs 3 times
5 occurs 1 times
1 occurs 2 times
4 occurs 1 times
The following example creates a Dictionary of key-value pairs, where the key corresponds to each distinct element and value is the number of times the key appears in the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int> { 2, 5, 1, 1, 2, 2, 4 }; var result = values.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count()); foreach (var g in result) { Console.WriteLine("{0} occurs {1} times", g.Key, g.Value); } } } |
Output:
2 occurs 3 times
5 occurs 1 times
1 occurs 2 times
4 occurs 1 times
Finally, to get the count of a single element, use the Where() method to filter the list to obtain matching values with the specified target and then find its frequency using the Count() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int> { 2, 5, 1, 1, 2, 2, 4 }; int target = 2; int count = values.Where(x => x.Equals(target)).Count(); Console.WriteLine("{0} occurs {1} times", target, count); } } |
Output:
2 occurs 3 times
That’s all about getting the frequency of all elements from a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)