如何使用Linq分组并求和项目

huangapple go评论64阅读模式
英文:

How to Group and Sum items using Linq

问题

我有以下格式的数据,我在C#的List对象中拥有:

Id  Value
1   5
2   3
3   -2
1   27
2   0
3   1
1   -4

我想要从这些数据创建一个三维List,格式如下:

Id  Count  TotalValue
1   3      28
2   2      3
3   2      -1

我不确定在LINQ中要使用什么语法来做到这一点,有人可以帮忙吗?

英文:

I have data in the following format which I have in a C# List object :

Id  Value
1   5
2   3
3   -2
1   27
2   0
3   1
1   -4

And I would like to create a 3 dimensional List from this data in the following format :

Id  Count  TotalValue
1   3      28
2   2      3
3   2      -1

I am not sure of the syntax to use in LINQ to do this, can anybody help?

答案1

得分: 1

你可以使用类似以下的代码:

var result = data.GroupBy(item => item.Id)
    .Select(group => new
    {
        Id = group.Key,
        Count = group.Count(),
        TotalValue = group.Sum(item => item.Value)
    })
    .ToList();
英文:

you can use something like this

var result = data.GroupBy(item => item.Id)
    .Select(group => new
    {
        Id = group.Key,
        Count = group.Count(),
        TotalValue = group.Sum(item => item.Value)
    })
    .ToList();

答案2

得分: 0

首先,您需要使用GroupBy方法。然后,您需要创建一个新对象,该对象接受每个分组并计算(CountSum)您想要的值:

DotNetFiddle示例

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var source = new List<(int Id, int Value)>
        {
            (1, 5),
            (2, 3),
            (3, -2),
            (1, 27),
            (2, 0),
            (3, 1),
            (1, -4),
        };

        var computed = source
             .GroupBy(x => x.Id)
             .Select(x => new { Id = x.Key, Count = x.Count(), TotalValue = x.Sum(s => s.Value) })
             .ToList();

        foreach (var value in computed)
        {
            Console.WriteLine($"{value.Id} {value.Count} {value.TotalValue}");
        }
    }
}

输出:

1 3 28

2 2 3

3 2 -1


<details>
<summary>英文:</summary>

First you&#39;ll want to use the [GroupBy](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=net-7.0)
Then you&#39;ll want to create a new object that takes each group and calculates ([Count](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count?view=net-7.0) and [Sum](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum?view=net-7.0)) the values to want from them:



[DotNetFiddle Example](https://dotnetfiddle.net/w9mgdG)

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
public static void Main()
{
var source = new List<(int Id, int Value)>
{
(1, 5),
(2, 3),
(3, -2),
(1, 27),
(2, 0),
(3, 1),
(1, -4),
};

	var computed = source
     .GroupBy(x =&gt; x.Id)
     .Select(x =&gt; new {Id = x.Key, Count = x.Count(), TotalValue = x.Sum(s =&gt; s.Value)})
     .ToList();
	
	foreach(var value in computed)
	{
		Console.WriteLine($&quot;{value.Id} {value.Count} {value.TotalValue}&quot;);
	}
}

}


Output:

&gt;1 3 28
&gt;
&gt;2 2 3
&gt;
&gt;3 2 -1


</details>



# 答案3
**得分**: -1

以下是已翻译的内容:

让我使用一个元组来表示一个对象

```csharp
var x = new List<(int Id, int Value)>();

var y = x.GroupBy(x => x.Id).Select(_ => new { Id = _.Key, Count = _.Count(), TotalValue = _.Sum(i => i.Value) });
英文:

Let me use a tuple for an object

var x = new List&lt;(int Id, int Value)&gt;();
            
var y = x.GroupBy(x =&gt; x.Id).Select(_ =&gt; new { Id = _.Key, Count = _.Count(), TotalValue = _.Sum(i =&gt; i.Value) });

huangapple
  • 本文由 发表于 2023年7月28日 01:38:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定