1

I have two lists with objects. They are of the same length. Each object has an ID (which is represented in both lists), a change date and some data. I want to create a new list with the same ID's but with the object with the more recent change date, with an efficient Linq statement.

Example:

List 1:

ID: 1 ChangeDate 12:00 Data 1:1
ID: 2 ChangeDate 13:00 Data 1:2 <-
ID: 3 ChangeDate 14:00 Data 1:3

List 2:

ID: 1 ChangeDate 12:05 Data 2:1 <-
ID: 2 ChangeDate 12:55 Data 2:2
ID: 3 ChangeDate 14:10 Data 2:3 <-

Result:

ID: 1 ChangeDate 12:05 Data 2:1 
ID: 2 ChangeDate 13:00 Data 1:2
ID: 3 ChangeDate 14:10 Data 2:3

Cheers

2
  • Is the order of both lists the same? Commented Sep 7, 2017 at 19:44
  • The order is not always the same. Commented Sep 7, 2017 at 19:46

1 Answer 1

2

If we suppose that you have a list which contains the lists you have mentioned:

var input = new List<Item> { list1, list2 };

where Item it the type of the objects that list1 and list2 include.

You can try the following:

var output = input.SelectMany(x=>x)
                  .GroupBy(x=>x.ID)
                  .Select(gr=>gr.OrderByDescending(x=>x.ChangeDate).First());

Essentially we project all the elements from the list in one list and then we group the items based on their ID. Then From each group we pick the most recent record.

If we have only the lists, we can concatenate them:

var input = list1.AddRange(list2);

and then try the following:

var output = input.GroupBy(x=>x.ID)
                  .Select(gr=>gr.OrderByDescending(x=>x.ChangeDate).First());
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent and elegant. Thank you!
Instead of putting both in an extra input list, you can just replace input.SelectMany(x => x) with list1.Union(list2).
@Jeremi Even better. Thank you.

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.