Given the following object:
public class Person
{
    public string Name {get; set;}
    public string Age {get; set;}
    public list<string> Interests {get; set;}
}
Is there a nice one line linq way to flatten this (I'm open to extension methods) so that if for example we have
var People = new List<Person>(){
    new Person(){
        Name = "Bill",
        Age  = 40,
        Interests = new List<string>(){"Football", "Reading"}
    },
    new Person = new List<Person>(){
        Name = "John",
        Age = 32,
        Interests = new List<string>(){ "Gameshows", "Reading"}
    },
    new Person = new List<Person>(){
        Name = "Bill",
        Age = 40,
        Interests = new List<string>(){ "Golf"} 
    }
} 
We can get a result of (i.e, AddRange to the Interests list property if other properties match):
{
    {
        Name = "Bill",
        Age  = 40,
        Interests = {"Football", "Reading", "Golf"}
    },
    {
        Name = "John",
        Age = 32,
        Interests = { "Gameshows", "Reading"}
    }
} 
                We can try GroupBy and SelectMany:
List<Person> People = ...
var result = People
  .GroupBy(person => new {
     person.Name,
     person.Age 
   })
  .Select(chunk => new Person() {
     Name      = chunk.Key.Name,
     Age       = chunk.Key.Age,
     Interests = chunk
       .SelectMany(item => item.Interests)
       .Distinct()
       .ToList()
   })
  .ToList(); // if we want List<People> 
                        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