分组并计入列表 [英] Group by and count in List
问题描述
我有一个用整数填充的列表,像这样:
I have an List which is filled with ints, like this:
[0] 1
[1] 4
[2] 4
[3] 8
[4] 9
[5] 1
[6] 1
所以基本上那里是随机数,但是同一数字在该列表中可能出现多次.
So basically random numbers in there, but the same number can occure multiple times in that list.
我想要的是按数字对它们进行分组,但是我还可以说出该数字在列表中的次数.这样我就有了类似的东西:
What i want is to group them by number, but that i can also tell how many times that number was in the list. So that i have a something like:
[0]
[number] 1
[total] 3 // Occured 3 times in the list
[1]
[number] 4
[total] 2
[2]
[number] 8
[total] 1
[3]
[number] 9
[total] 1
是否有快速/简便的方法来完成此任务?还是我可以写出各种循环并进行检查以手动构造类似的东西?
Is there a fast/easy way to accomplish this? Or do i have the write out all sorts of loops and checks to construct something like this manually?
推荐答案
使用 GroupBy
和 Count
:
var numberGroups = numbers.GroupBy(i => i);
foreach(var grp in numberGroups)
{
var number = grp.Key;
var total = grp.Count();
}
这是另一个使用匿名类型存储一些信息的示例.由于它似乎是理想的结果,因此它还会创建一个数组:
Here's another example which uses an anonymous type to store some informations. It also creates an array since it seems to be the desired result:
var numberGroups = numbers.GroupBy(i => i)
.Select(grp => new{
number = grp.Key,
total = grp.Count(),
average = grp.Average(),
minimum = grp.Min(),
maximum = grp.Max()
})
.ToArray();
foreach (var numInfo in numberGroups)
{
var number = numInfo.number;
// ...
var maximum = numInfo.maximum;
}
这篇关于分组并计入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!