Bagaboo
Bagaboo

Reputation: 363

Linq to select objects from two lists based on content

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

Upvotes: 1

Views: 1859

Answers (1)

Christos
Christos

Reputation: 53958

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

Upvotes: 2

Related Questions