Combine 2 lists based on one property and combine 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}}}

I want to combine 2 lists so that the resulting list is

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

Since the identifier of the first element of the 2 lists was the same, they became a single entity, and one of their properties was combined.
I can do a for loop to achieve this, but I am looking for an optimal linq expression for this.

Thank you

+4
source share
2 answers

Concatlists together, GroupById Property SelectMany, to get a combined list of elements:

ob1.Concat(ob2)
   .GroupBy(o => o.Id)
   .Select(g => new MyObject() 
   { 
      Id = g.Key, 
      Items = g.SelectMany(o => o.Items ).Distinct().ToList()
   });
+5
source

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
0

Source: https://habr.com/ru/post/1610829/


All Articles