C# 展平具有列表属性的对象列表

Sea*_*n T 4 c# linq flatten

给定以下对象:

public class Person
{
    public string Name {get; set;}

    public string Age {get; set;}

    public list<string> Interests {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

是否有一种很好的单行 linq 方法来展平它(我对扩展方法持开放态度),例如,如果我们有

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"} 
    }
} 
Run Code Online (Sandbox Code Playgroud)

我们可以得到以下结果(即,Interests如果其他属性匹配,则 AddRange 到列表属性):

{
    {
        Name = "Bill",
        Age  = 40,
        Interests = {"Football", "Reading", "Golf"}
    },
    {
        Name = "John",
        Age = 32,
        Interests = { "Gameshows", "Reading"}
    }
} 
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 6

我们可以尝试GroupBySelectMany

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> 
Run Code Online (Sandbox Code Playgroud)