9

给定以下列表:

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

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

IE。想以 yp 结尾:

{
    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

4

2 回答 2

20

为什么不用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) 连接起来的方法。

于 2013-04-03T10:18:36.590 回答
5
data.GroupBy(x => x.category).Select(g => new
    {
        category = g.Key,
        description = g.Select(x => x.text).Aggregate((s1, s2) => s1 + "," + s2)
     });
于 2018-09-16T19:07:21.590 回答