How to get frequency of elements from List in c#

陌路散爱 提交于 2019-12-06 12:46:19

问题


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.


回答1:


using System.Linq;

List<int> ids = //

foreach(var grp in ids.GroupBy(i => i))
{
    Console.WriteLine("{0} : {1}", grp.Key, grp.Count());
}



回答2:


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.




回答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);
}


来源:https://stackoverflow.com/questions/17434119/how-to-get-frequency-of-elements-from-list-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!