Linq GroupBy和Aggregate

smo*_*sen 6 linq group-by aggregate

鉴于以下列表:

var data = new[]
    {
        new {category = "Product", text = "aaaa"},
        new {category = "Product", text = "bbbb"},
        new {category = "Product", text = "bbbb"},
    };
Run Code Online (Sandbox Code Playgroud)

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

即.想结束yp:

{
    categroy="Product"
    description = "aaaa,bbbb,cccc"
}
Run Code Online (Sandbox Code Playgroud)

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

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

TIA

Mar*_*zek 10

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

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

有了Aggregate你应该做以下几点:

    description = g.Aggregate(string.Empty, (x, i) => x + "," + i.text)
Run Code Online (Sandbox Code Playgroud)

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


小智 9

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

  • 这如何改善可接受的答案?另外,仅仅提供代码片段作为答案并不是很有帮助。稍微解释一下为什么这是一个好的解决方案,可以帮助 OP 和未来的读者。 (3认同)