C # LINQ Select objects with the same value of one value combining the properties of others

I have a list of such products:

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

I want to do the following:

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

I always want to use prods with the same id and add their colors. I feel there is a smart way to create a code string, but I was somehow stuck with:

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

which does not allow me to add a second color. Any help is appreciated

+4
source share
2 answers

Try it.

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)) 
               }); 

Job Demo

+11
source

, , ( ).

:

public class Program
{
    public static void Main()
    {
        List<Product> products = new List<Product>
        {
            new Product() {Id = 1, Name="name1", Color="Blue"},
            new Product() {Id = 1, Name="name1", Color="Green"},
            new Product() {Id = 1, Name="name1", Color="Green"},
            new Product() {Id = 2, Name="name2", Color="Red"}
        };

        var results = from product in products
            group product by product.Id into g // there is no need to group by a complex key if product.Id is unique per product
            let colors = string.Join(",", g.Select(c=> c.Color).Distinct()) 
            let p = g.First().Color = colors
            select g.First();

        foreach(var result in results)
            Console.WriteLine(result);          
    }
}

public class Product
{
    public int Id;
    public string Name;
    public string Color;

    public override string ToString()
    {
        return string.Format("Id:\"{0}\", Name:\"{1}\", Color:\"{2}\"", Id, Name, Color);
    }
}

"" id = 1, .

:

Id:"1", Name:"name1", Color:"blue,Green"
Id:"2", Name:"name2", Color:"Red"

: https://dotnetfiddle.net/HLtHIE

, , .

0

Source: https://habr.com/ru/post/1629860/


All Articles