使用Linq比较两个列表
本文关键字:两个 列表 Linq 比较 使用 | 更新日期: 2023-09-27 18:10:12
好了,我有一个列表,我想把名字相同的对象组合成一个,并把兄弟姐妹添加到其他兄弟姐妹列表中。
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"}
}
}
您当前连接列表的方式不应该工作,否则您需要:
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();
我觉得这样应该可以。
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
});