4

I am trying to get the frequency of elements stored in a list.

I am storing the following ID's in my list

ID
1
2
1
3
3
4
4
4

I want the following output:

ID| Count
1 | 2
2 | 1
3 | 2
4 | 3

In java you can do the following way.

for (String temp : hashset) 
    {
    System.out.println(temp + ": " + Collections.frequency(list, temp));
    }

Source:http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/

How to get the frequency count of a list in c#?

Thanks.

Huzaifa
  • 1,111
  • 5
  • 20
  • 37

3 Answers3

19

You can use LINQ

var frequency = myList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());

This will create a Dictionary object where the key is the ID and the value is the number of times the ID appears.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
9
using System.Linq;

List<int> ids = //

foreach(var grp in ids.GroupBy(i => i))
{
    Console.WriteLine("{0} : {1}", grp.Key, grp.Count());
}
Lee
  • 142,018
  • 20
  • 234
  • 287
3
int[] randomNumbers =  { 2, 3, 4, 5, 5, 2, 8, 9, 3, 7 };
Dictionary<int, int> dictionary = new Dictionary<int, int>();
Array.Sort(randomNumbers);

foreach (int randomNumber in randomNumbers) {
    if (!dictionary.ContainsKey(randomNumber))
        dictionary.Add(randomNumber, 1);
    else
        dictionary[randomNumber]++;
    }

    StringBuilder sb = new StringBuilder();
    var sortedList = from pair in dictionary
                         orderby pair.Value descending
                         select pair;

    foreach (var x in sortedList) {
        for (int i = 0; i < x.Value; i++) {
                sb.Append(x.Key+" ");
        }
    }

    Console.WriteLine(sb);
}
Gaëtan Maisse
  • 12,208
  • 9
  • 44
  • 47
jack
  • 31
  • 1