Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq GroupBy and Aggregate

Given the following list:

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

how do I group it by category and return an object with category and a description of the different text put together ??

ie. would like to end yp with:

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

tried the following GroupBy and Aggregate, but something is not right

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

TIA

like image 218
smolesen Avatar asked Apr 03 '13 10:04

smolesen


People also ask

What is aggregate function Linq?

In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.


1 Answers

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

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

With Aggregate you should do following:

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

First parameter sets seed start value to String.Empty. Second parameter defines method to concatenate current seed value (string) with current element (anonymous_type).

like image 199
MarcinJuraszek Avatar answered Sep 22 '22 09:09

MarcinJuraszek