[英]How to get frequency of elements from List in c#
I am trying to get the frequency of elements stored in a list. 我正在尝试获取存储在列表中的元素的频率。
I am storing the following ID's in my list 我将以下ID存储在列表中
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. 在Java中,您可以执行以下方式。
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/ 来源: http : //www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/
How to get the frequency count of a list in c#? 如何在C#中获取列表的频率计数?
Thanks. 谢谢。
You can use LINQ 您可以使用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. 这将创建一个
Dictionary
对象,其中的键是ID
,值是ID出现的次数。
using System.Linq;
List<int> ids = //
foreach(var grp in ids.GroupBy(i => i))
{
Console.WriteLine("{0} : {1}", grp.Key, grp.Count());
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.