Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# flatten a list of objects with a list property [duplicate]

Tags:

c#

flatten

linq

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"}
    }
} 
like image 303
Sean T Avatar asked Jan 25 '23 23:01

Sean T


1 Answers

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> 
like image 68
Dmitry Bychenko Avatar answered Jan 30 '23 07:01

Dmitry Bychenko