C#如何将具有列表属性的对象列表展开为一个列表

5

给定以下对象:

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

    public string Age {get; set;}

    public list<string> Interests {get; set;}
}

这里有一个一行的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"} 
    }
} 

我们可以得到一个结果(即,如果其他属性匹配,则将内容添加到Interests列表属性中):
{
    {
        Name = "Bill",
        Age  = 40,
        Interests = {"Football", "Reading", "Golf"}
    },
    {
        Name = "John",
        Age = 32,
        Interests = { "Gameshows", "Reading"}
    }
} 

您的意思是将每个兴趣放在单独的一行上来进行展开吗? - jdweng
@jdweng 不好意思,我不是在压平对象,只是确保没有多个相同的对象,因为列表属性具有其他值。 - Sean T
2个回答

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> 

谢谢,SelectMany 就是我想要的 :) - Sean T

3
你可以使用 GroupBySelectMany 来拼接兴趣。
People.GroupBy(c => new
        {
            c.Name,
            c.Age
        })
       .Select(g => new Person() 
                  { Name = g.Key.Name, 
                    Age = g.Key.Age,
                    Interests = g.SelectMany(r => r. Interests).ToList()})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接