Applying aggregate functions to multiple properties with LINQ GroupBy

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 12:28:48

问题


I have a list of Object (it's called: sourceList)
Object contains: Id, Num1, Num2, Num3, Name, Lname

Assume I have the following list:

1, 1, 5, 9, 'a', 'b'
1, 2, 3, 2, 'b', 'm'
2, 5, 8, 7, 'r', 'a'

How can I return another list (of object2) that returns a new list:

Id, sum of num1, sum of num2

For the example above, it should return a list of object2 that contains:

1, 3, 8
2, 5, 8

I tried:

Dim a = sourceList.GroupBy(Function(item) item.Id).
        Select(Function(x) x.Sum(Function(y) y.Num1)).ToList()

But I don't know how to sum num2.


回答1:


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.)



来源:https://stackoverflow.com/questions/27365169/applying-aggregate-functions-to-multiple-properties-with-linq-groupby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!