Pregunta

Supposing I have the following list

        var list = new List<CustomClass>
        {
            new CustomClass {Group = "Car", Color = "White"},
            new CustomClass {Group = "Motocycle", Color = "Blue"},
            new CustomClass {Group = "Car", Color = "Black"},
        };

How do I set this list to be distinct by Group and merge the Color with commas, such that my list will be:

Group            Color
------------------------------------
"Car"           "White, Black"
"Motocycle"     "Blue"
¿Fue útil?

Solución

Assuming you want a new List of CustomClass use string.join and groupby

var list = new List<CustomClass>
{
    new CustomClass {Group = "Car", Color = "White"},
    new CustomClass {Group = "Motocycle", Color = "Blue"},
    new CustomClass {Group = "Car", Color = "Black"},
};

var results = list.GroupBy(c => c.Group).Select(g => new CustomClass()
    {
        Group = g.Key,
        Color = String.Join(", ", g.Select(c=>c.Color))
    }).ToList();

Otros consejos

I'm not sure what structure you want to store the result in.

This will give you a dictionary with the results you want.

var colors =
    list.GroupBy(x => x.Group)
        .ToDictionary(x => x.Key, x => string.Join(", ", x.Select(y => y.Color)));

Try this:

    var query =
        from x in list
        group x.Color by x.Group into gcs
        select new
        {
            Group = gcs.Key,
            Colors = String.Join(", ", gcs),
        };

I get this result:

result

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top