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
.
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.
Tested this and it seems to work fine. (The equivalent fluent style is
which also works great and is arguably a bit easier to read.)