例如,如何使用LINQ按GroupId
对以下记录进行分组,并(从而将每个组中的所有行合并为一个)
var list = new List<Foo>()
{
new Foo() { GroupId = 0, ValueA = 10, ValueB = 100 },
new Foo() { GroupId = 1, ValueA = 30, ValueB = 700 },
new Foo() { GroupId = 1, ValueA = 40, ValueB = 500 },
new Foo() { GroupId = 2, ValueA = 80, ValueB = 300 },
new Foo() { GroupId = 2, ValueA = 20, ValueB = 200 },
new Foo() { GroupId = 2, ValueA = 20, ValueB = 200 }
};
请告诉我如何使用单独的逗号添加这些不添加这些值 预期结果是:
| GroupId | ValueA | ValueB |
|---------|--------|-----------|
| 0 | 10 | 100 |
| 1 | 30,40 | 700,500 |
| 2 |80,20,20|300,200,200|
我可以用代码添加这些:
list.GroupBy(i => i.GroupId)
.Select(g => new { GroupId = g.Key,
ValueA = g.Sum(i => i.ValueA),
ValueB = g.Sum(i => i.ValueB)});
但我需要用分隔的逗号显示值 谢谢你的帮助
答案 0 :(得分:1)
使用String.Join
并选择字符串代替:
list.GroupBy(i => i.GroupId)
.Select(g => new {
GroupId = g.Key,
ValueA = String.Join(",", g.Select(i => i.ValueA.ToString())),
ValueB = String.Join(",", g.Select(i => i.ValueB.ToString()))
});
答案 1 :(得分:0)
您可以使用string.Join命令将各个数字与分隔符(,)连接。