IList<MyObject> ob1 = {new MyObject {Id = "1", Items = {BananaObject1, BananaObject2}}}
IList<MyObject> ob2 = { new MyObject {Id = "1", Items = {BananaObject2, BananaObject3}},
new MyObject {Id = "2", Items = {BananaObject3, BananaObject3}}}
我想合并这两个列表,使结果列表为
IList<MyObject> ob2 = { new MyObject {Id = "1", Items = {BananaObject1, BananaObject2, BananaObject3}},
new MyObject {Id = "2", Items = {BananaObject3, BananaObject3}}}
因此,由于两个列表中第一项的id是相同的,因此它们成为一个,并且它们的一个属性被连接在一起。
我可以做一个for循环来实现这一点,但我正在寻找一个整洁的最佳性能linq表达式。
谢谢
Concat
的列表在一起,GroupBy
的Id属性,SelectMany
得到合并列表的项目:
ob1.Concat(ob2)
.GroupBy(o => o.Id)
.Select(g => new MyObject()
{
Id = g.Key,
Items = g.SelectMany(o => o.Items ).Distinct().ToList()
});
Use MoreLINQ:
obj1.FullGroupJoin(obj2,
a=>a.Id,
b=>b.Id,
(id,a,b)=>new {id=id,Items=a.Items.Union(b.Items)},
new {id=-1, Items=new List<string>()}, //Default for left side
new {id=-2, Items=new List<string>()});//Default for right side