[ACCEPTED]-How to merge two lists using LINQ?-linq

Accepted answer
Score: 19

I would strongly recommend against using 17 string-concatenation to represent this information; you 16 will need to perform unnecessary string-manipulation 15 if you want to get the original data back 14 later from the merged list. Additionally, the 13 merged version (as it stands) will become 12 lossy if you ever decide to add additional 11 properties to the class.

Preferably, get 10 rid of the Merge method and use an appropriate 9 data-structure such as a multimap that can 8 each map a collection of keys to one or 7 more values. The Lookup<TKey, TElement> class can serve this purpose:

var personsById = list1.Concat(list2)
                       .ToLookup(person => person.ID);

Anyway, to 6 answer the question as asked, you can concatenate 5 the two sequences, then group persons by 4 their ID and then aggregate each group into 3 a single person with the provided Merge method:

var mergedList = list1.Concat(list2)
                      .GroupBy(person => person.ID)
                      .Select(group => group.Aggregate(
                                         (merged, next) => merged.Merge(next)))

EDIT: Upon 2 re-reading, just realized that a concatenation 1 is required since there are two lists.

More Related questions