13

How to merge two lists using LINQ like the following:

class Person
{
    public int ID { get; set;}
    public string Name { get; set;}
    public Person Merge( Person p)
    {
         return new Person { ID = this.ID, Name = this.Name + " " + p.Name };
    } 
}

I have two List of person:

list1:
1, A
2, B

list2: 
2, C
3, D

I want the result like the following

result: 
1, A
2, B C
3, D

Any help!

1 Answer 1

19

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

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

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

Anyway, to answer the question as asked, you can concatenate the two sequences, then group persons by their ID and then aggregate each group into 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)))
                      .ToList();

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the advice, but the posted code is just a sample for the idea, not my real code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.