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

I want to merge the 2 lists such that the resulting list would be

IList<MyObject> ob2 = { new MyObject {Id = "1", Items = {BananaObject1, BananaObject2, BananaObject3}},
new MyObject {Id = "2", Items = {BananaObject3, BananaObject3}}}

So since the id of the first item of the 2 lists were the same, they became one, and one of their property is concatenated.
I can do a for loop to achieve this, but I am looking for a neat best performance linq expression for this.

thank you

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
E. K.
  • 63
  • 1
  • 6
  • If the `Items` in one `MyObject` already contain a duplicate (like in the case of `ob2[1].Items` containing a duplicate of `BananaObject3`), do you want to keep the duplication? – Yacoub Massad Oct 08 '15 at 18:35
  • Possible duplicate of [LINQ - Full Outer Join](http://stackoverflow.com/questions/5489987/linq-full-outer-join) – Robert McKee Oct 08 '15 at 18:47
  • I don't want to keep the duplication, thanks! – E. K. Oct 08 '15 at 19:26

2 Answers2

6

Concat the lists together, GroupBy Id property, SelectMany to get the merged list of items:

ob1.Concat(ob2)
   .GroupBy(o => o.Id)
   .Select(g => new MyObject() 
   { 
      Id = g.Key, 
      Items = g.SelectMany(o => o.Items ).Distinct().ToList()
   });
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
0

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
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • Sorry, I guess FullGroupJoin hasn't made it into the main branch yet, but here's the code: https://github.com/fsateler/MoreLINQ/blob/full-outer/MoreLinq/FullGroupJoin.cs – Robert McKee Oct 08 '15 at 18:41
  • Another answer is available here as well: http://stackoverflow.com/questions/5489987/linq-full-outer-join – Robert McKee Oct 08 '15 at 18:46