Linq GroupBy and the aggregate

Given the following list:

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

how can I group it into categories and return an object with a category and description of another text put together

T. would like to end yp:

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

tried the following GroupBy and Aggregate, but something was wrong.

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

TIA

+6
source share
2 answers

Why don't you use the method String.Join(IEnumerable)?

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

With Aggregateyou should do the following:

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

The first parameter sets the initial value of the seed String.Empty. The second parameter defines the method for concatenating the current initial value ( string) with the current element ( anonymous_type).

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

All Articles