Linq GroupBy和Aggregate

问题描述 投票:6回答:2

鉴于以下列表:

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

linq group-by aggregate
2个回答
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)连接起来的方法。


2
投票
data.GroupBy(x => x.category).Select(g => new
    {
        category = g.Key,
        description = g.Select(x => x.text).Aggregate((s1, s2) => s1 + "," + s2)
     });
© www.soinside.com 2019 - 2024. All rights reserved.