【问题标题】:C# flatten a list of objects with a list property [duplicate]C#使用列表属性展平对象列表[重复]
【发布时间】:2019-12-15 04:35:28
【问题描述】:

给定以下对象:

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"} 
    }
} 

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

{
    {
        Name = "Bill",
        Age  = 40,
        Interests = {"Football", "Reading", "Golf"}
    },
    {
        Name = "John",
        Age = 32,
        Interests = { "Gameshows", "Reading"}
    }
} 

【问题讨论】:

  • 你的意思是扁平化将每个兴趣放在单独的行上吗?
  • @jdweng 不抱歉,没有展平对象 - 只是确保没有多个相同的对象,因为列表属性在中具有附加值

标签: c# linq flatten


【解决方案1】:

我们可以试试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 是我所追求的 :)
【解决方案2】:

您可以使用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()})

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多