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:

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

Output:

2 occurs 3 times

That’s all about getting the frequency of all elements from a list in C#.