Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ Select objects with the same value of one property join values of other

I have a list of prods like this:

Prod1: Id=1, Name="name1", Color="Blue"
Prod2: Id=1, Name="name1", Color="Green"
Prod3: Id=2, Name="Test2, Color="Red"

What I want to perform is to get reduced list like this:

Prod1: Id=1, Name="name1", Color="Blue, Green"
Prod3: Id=2, Name="Test2, Color="Red"

I always want to take prods with the same id and add up their colors. I feel there is a clever one code line way to do this, but I somehow got stuck with:

productList.GroupBy(p => new { p.Id }).Select(x => x.First()).ToList();

which does not give me an ability to add second color. Will apreciate any help

like image 449
cAMPy Avatar asked Feb 22 '16 08:02

cAMPy


1 Answers

Try this.

productList.GroupBy(p => new { p.Id, p.Name })
           .Select(x =>new {
                      Id =x.Key.Id, 
                      Name = x.Key.Name,
                      Color = String.Join(",", x.Select(c=> c.Color)) 
               }); 

Working Demo

like image 183
Hari Prasad Avatar answered Sep 22 '22 08:09

Hari Prasad