Linq GroupBy和Aggregate

时间:2013-04-03 10:17:05

标签: linq group-by aggregate

给出以下列表:

var data = new[]
    {
        new {category = "Product", text = "aaaa"},
        new {category = "Product", text = "bbbb"},
        new {category = "Product", text = "bbbb"},
    };

如何按类别对其进行分组并返回一个带有类别的对象和放在一起的不同文本的描述?

即。我希望以下结尾:

{
    categroy="Product"
    description = "aaaa,bbbb,cccc"
}

尝试了以下GroupBy和Aggregate,但有些事情不对

data.GroupBy(x => x.category).Select(g => new
    {
        category = g.Key,
        description = g.Aggregate((s1, s2) => s1 + "," + s2)
     });

TIA

2 个答案:

答案 0 :(得分:10)

为什么不使用String.Join(IEnumerable)方法?

data.GroupBy(x => x.category).Select(g => new
{
    category = g.Key,
    description = String.Join(",", g.Select(x => x.text))
});

使用Aggregate,您应该执行以下操作:

    description = g.Aggregate(string.Empty, (x, i) => x + "," + i.text)

第一个参数将种子起始值设置为String.Empty。第二个参数定义了将当前种子值(string)与当前元素(anonymous_type)连接起来的方法。

答案 1 :(得分:2)

data.GroupBy(x => x.category).Select(g => new
    {
        category = g.Key,
        description = g.Select(x => x.text).Aggregate((s1, s2) => s1 + "," + s2)
     });