如何从c#中获取List中元素的频率

我试图获取存储在列表中的元素的频率。

我将以下ID存储在我的列表中

ID 1 2 1 3 3 4 4 4 

我想要以下输出:

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

在java中,您可以执行以下方法。

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

资料来源: http : //www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/

如何获取c#中列表的频率计数?

谢谢。

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

您可以使用LINQ

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

这将创建一个Dictionary对象,其中键是ID ,值是ID出现的次数。

 int[] randomNumbers = { 2, 3, 4, 5, 5, 2, 8, 9, 3, 7 }; Dictionary dictionary = new Dictionary(); 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); }