使用LINQ GroupBy将聚合函数应用于多个属性 [英] Applying aggregate functions to multiple properties with LINQ GroupBy
问题描述
我有一个 Object
的列表(它称为: sourceList
)
Object
包含:Id,Num1,Num2,Num3,名称,Lname
I have a list of Object
(it's called: sourceList
)
Object
contains: Id, Num1, Num2, Num3, Name, Lname
假设我有以下列表:
1, 1, 5, 9, 'a', 'b'
1, 2, 3, 2, 'b', 'm'
2, 5, 8, 7, 'r', 'a'
如何返回另一个列表(由 object2
组成),该列表返回一个新列表:
How can I return another list (of object2
) that returns a new list:
Id, sum of num1, sum of num2
对于上面的示例,应该返回包含以下内容的 object2
列表:
For the example above, it should return a list of object2
that contains:
1, 3, 8
2, 5, 8
我尝试过:
Dim a = sourceList.GroupBy(Function(item) item.Id).
Select(Function(x) x.Sum(Function(y) y.Num1)).ToList()
但是我不知道如何对 num2
求和。
But I don't know how to sum num2
.
推荐答案
您需要的是将匿名类型与初始化程序表达式组合在一起,这是流利风格的LINQ隐式执行的方式。因此,例如
What you need is to combine anonymous types with initializer expressions, which is the way LINQ in fluent style does it implicitly. So e.g.
Dim a = sourceList.GroupBy(Function(item) item.Id).
Select(Function(x) New With {.Id = x.Key,
.Sum1 = x.Sum(Function(y) y.Num1),
.Sum2 = x.Sum(Function(y) y.Num2),
.Sum3 = x.Sum(Function(y) y.Num3)}).ToList()
对此进行了测试,它似乎可以正常工作。 (等效的流利风格是
Tested this and it seems to work fine. (The equivalent fluent style is
Dim fluent = (From item In sourceList
Group By item.Id Into Sum1 = Sum(item.Num1),
Sum2 = Sum(item.Num2),
Sum3 = Sum(item.Num3)).ToList()
它也很好用,可以说更容易阅读。)
which also works great and is arguably a bit easier to read.)
这篇关于使用LINQ GroupBy将聚合函数应用于多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!