基于一个属性合并2个列表并连接其他属性

时间:2015-10-08 18:13:08

标签: c# linq join ienumerable sql-to-linq-conversion

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}}}

因此,由于2个列表中第一个项目的ID相同,因此它们成为一个,并将其中一个属性连接起来。
我可以做一个for循环来实现这个目标,但我正在为此寻找一个整洁的最佳性能linq表达式。

谢谢

2 个答案:

答案 0 :(得分:6)

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()
   });

答案 1 :(得分:0)

使用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