好的,我有一个列表,我想将具有相同名字的对象合并为一个,并将兄弟姐妹添加到其他兄弟姐妹列表中。
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"}
}
}
答案 0 :(得分:4)
您目前的连接列表方式不起作用,否则您需要:
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();
答案 1 :(得分: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
});