英文:
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方法。然后,您需要创建一个新对象,该对象接受每个分组并计算(Count和Sum)您想要的值:
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'll want to use the [GroupBy](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=net-7.0)
Then you'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 => 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}");
}
}
}
Output:
>1 3 28
>
>2 2 3
>
>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<(int Id, int Value)>();
var y = x.GroupBy(x => x.Id).Select(_ => new { Id = _.Key, Count = _.Count(), TotalValue = _.Sum(i => i.Value) });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论