问题
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