Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 318
E. K. Avatar asked Oct 08 '15 18:10

E. K.


1 Answers

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()
   });
like image 191
Jakub Lortz Avatar answered Nov 14 '22 23:11

Jakub Lortz