根据一个 属性 合并 2 个列表并连接其他属性
Merge 2 lists based on one property and concatenate other properties
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}}}
我想合并 2 个列表,这样生成的列表将是
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()
});
使用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
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}}}
我想合并 2 个列表,这样生成的列表将是
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()
});
使用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