Buda Gavril Buda Gavril - 1 year ago 76
C# Question

Linq: group objects and remove duplicate elements from their child elements

So I have this class structure:

public class ObjectCode
{
public string Code { get; set; }
}

class Configuration
{
public int Id { get; set; }

public string Name { get; set; }

public IEnumerable<ObjectCode> Objects { get; set; }
}


I am receiving a list of
Configuration
from multiple providers. My problem is that I don't know how to group these objects by Id and put the distinct
ObjectCode
objects from all the
Configuration
objects in the resulting entity.

Answer Source

Use SelectMany inside each group in GroupBy:

var res = congigs
    .GroupBy(c => new {c.Id, c.Name})
    .Select(g =>
        new Configuration {
            Id = g.Key.Id
        ,   Name = g.Key.Name
        ,   Objects = g
               .SelectMany(c => c.Objects)
               .GroupBy(c => c.Code)
               .Select(gg => gg.First())
        }
    ).ToList();

The above assumes that Config objects with the same Id also have identical Names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download