C# 在列表中分组和计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10600129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:26:23  来源:igfitidea点击:

Group by and count in List

c#

提问by w00

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?

有没有快速/简单的方法来实现这一目标?或者我是否有写出各种循环和检查来手动构造这样的东西?

采纳答案by Tim Schmelter

Use GroupByand Count:

使用GroupByCount

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;
}

回答by Nikhil Agrawal

Use this

用这个

var result = numbers.GroupBy(n => n)
                    .Select(c => new { Key = c.Key, total = c.Count() });

回答by Jamie Dixon

Using Tims method from above with a Select rather than a foreach you could do:

将上面的 Tims 方法与 Select 而不是 foreach 一起使用,您可以执行以下操作:

var itemsByGroupWithCount = numbers.GroupBy(i => i)
                 .Select(item => new { 
                        Number = item.Key, 
                        Total = item.Count()});

回答by Marc

Here's an example of all sorts of loops and checks:

这是各种循环和检查的示例:

var items = new Dictionary<int,int>();
foreach(var number in numbers)
{
   if(items.ContainsKey(number))
      items[number]++;
   else
      items.Add(number, 1);
}

Just for reference anyway. I prefer the LINQ approach, but it's not really as bad of a problem as you may have believed.

反正仅供参考。我更喜欢 LINQ 方法,但它并没有您想象的那么严重。

回答by solmon

My solution:

我的解决方案:

var result = from i in n 
group i by i into g
select new {g.Key, Count= g.Count()};

回答by pvsfair

Using only the GroupBymethod you could do it like this:

仅使用GroupBy您可以这样做的方法:

var itemsResult = numbers.GroupBy(i => i,
                                  i => i,
                                  (keys, numbersGrouped) =>
                                      new{
                                          number = numbersGrouped.FirstOrDefault(),
                                          total = numbersGrouped.Count()
                                      }
                                  );

It outperforms the GroupBy + Selectmethod proposed by the others executing in less than a half of the time comparing to the other implementations.

GroupBy + Select与其他实现相比,它在不到一半的时间内执行其他人提出的方法。

You can check below the performance comparison:

您可以查看下面的性能比较:

https://dotnetfiddle.net/0M2aKD

https://dotnetfiddle.net/0M2aKD

This is the docsfor the function used if you want to check how does it works

如果您想检查它是如何工作的,这是所用函数的文档