【问题标题】:Using Linq to Compare two Lists [closed]使用 Linq 比较两个列表 [关闭]
【发布时间】:2014-06-25 18:09:29
【问题描述】:

好的,我有一个列表,我想将具有相同名字的对象合并为一个,并将兄弟姐妹添加到其他兄弟姐妹列表中。

public class People
{ 
    string Name {get; set;}
    List<string> siblings {get; set;}
}

现在我有一个看起来像

的列表
 List<People> list3 = new List<People> 
 {  
     new People
     {
        name = "Chris",
        siblings = {"Richard"}
     },
     new People
     {
        name = "Billy",
        siblings = {"Thomas"}
     },
     new People
     {
        name = "Bob",
        siblings = {"Charles"}
     },
     new People
     {
        name = "Chris",
        siblings = {"Simon"}
     }
 }

现在我希望它变成:

 List<People> list3 = new List<People> 
 {  
     new People
     {
        name = "Chris",
        siblings = {"Richard", "Simon"}
     },
     new People
     {
        name = "Billy",
        siblings = {"Thomas"}
     },
     new People
     {
        name = "Bob",
        siblings = {"Charles"}
     }
 }

【问题讨论】:

  • 您的代码首先在属性名称和兄弟姐妹初始化上有错误。
  • @RyanEmerle 刚刚尝试使用 select 进行 selectMany

标签: c# .net linq list


【解决方案1】:

您当前的连接列表方式不应该工作,否则您需要:

var query = list3.GroupBy(r => r.Name)
                .Select(grp => new People
                {
                    Name = grp.Key,
                    Siblings = grp.SelectMany(r => r.Siblings).ToList(),
                });

要获得一个组合列表,您可以这样做:

List<People> list3 = list1.Concat(list2).ToList();

【讨论】:

    【解决方案2】:

    我认为这样的事情应该可行。

    var list3 = list2.Concat(list1).GroupBy(p => p.name)
        .Select(g => new People{
            name= g.Key, 
            siblings = from p in g
                       from s in p.siblings
                       select s
        });
    

    【讨论】:

    • +1,也可以是这样的:siblings = g.SelectMany(p=&gt;p.siblings)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多