Page 1 of 1

concatenate rows

Posted: Tue 28 Jul 2009 09:37
by actuary
Hi all,

I have written a bit of linq where it gets data from the db in the form of

Id Name Category
1 Name1 Cat1
2 Name2 Cat1
3 Name1 Cat3

I am trying to merge Category column for same Ids, something like:

Id Name Category
1 Name1 Cat1, Cat3
2 Name2 Cat1

How is this possible in LINQ? My statement is

var query = from p in table
select new {p.Id, p.Name, p.Category}

Any help would be appreciated.

Thanks

Posted: Tue 28 Jul 2009 12:57
by AndreyR
Here is one of possible solutions:

Code: Select all

        List ncs = new List();
        foreach (var el in from it in db.Namecategories group it by it.Name) {
          string categories = null;
          foreach (var cat in el) {
            if (categories != null)
              categories += ", ";
            categories += cat.Category;
          }
          ncs.Add(new Namecategory
          {
            Name = el.Key,
            Category = categories
          });
        }