例如,如何使用LINQ将GroupId中的以下记录分组,并将每个组中的所有其他列合并? (从而将每组中的所有行合并为一个)
var list = new List<Foo>() { new Foo() { GroupId = 0,ValueA = 10,ValueB = 100 },new Foo() { GroupId = 1,ValueA = 30,ValueB = 700 },ValueA = 40,ValueB = 500 },new Foo() { GroupId = 2,ValueA = 80,ValueB = 300 },ValueA = 20,ValueB = 200 },ValueB = 200 } };
预期成果为:
| GroupId | ValueA | ValueB | |---------|--------|--------| | 0 | 10 | 100 | | 1 | 70 | 1200 | | 2 | 120 | 700 |
解决方法
list.GroupBy(i => i.GroupId) .Select(g => new { GroupId = g.Key,ValueA = g.Sum(i => i.ValueA),ValueB = g.Sum(i => i.ValueB)});
或者只是为了乐趣,你可以在一个GroupBy调用中使用它的重载来做到这一点:
list.GroupBy(i => i.GroupId,(key,groupedItems) => new { GroupId = key,ValueA = groupedItems.Sum(i => i.ValueA),ValueB = groupedItems.Sum(i => i.ValueB),});
或者您可以使用Aggregate来避免迭代每个组多次:
list.GroupBy(i => i.GroupId) .Select(g => g.Aggregate((i1,i2) => new Foo{ GroupId = i1.GroupId,ValueA = i1.ValueA + i2.ValueA,ValueB = i1.ValueB + i2.ValueB,}));