Search code examples
c#linqjoinienumerablesql-to-linq-conversion

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


Solution

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