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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With