Philipp Elhaus
Philipp Elhaus

Reputation: 124

Merge two collections, in case of duplicate elements pick the one with the latest date

I've got two collections of objects that are of the form

class Point
{
    string name;
    DateTime date;
    int val;
}

Collections to merge are of different sizes (sometimes equal, sometimes not), occasionally they have entries that have the same name. I want to merge both collections into one and in case i have two entries with the same name i want to only keep the instance with the most recent date.

I initially thought i'd do this in 30secs but i'm breaking my legs here for over 2h now. I came up with a manual solution but it's horribly inefficient and overly complex. Asking if someone knows a short & performant LINQ 1-2 liner for a problem like that.

Upvotes: 0

Views: 117

Answers (1)

Nannanas
Nannanas

Reputation: 631

try

firstPoints
  .Concat(secondPoints)
  .groupBy(point => point.Name)
  .Select(points => points.OrderBy(point => point.Date).Last());

Upvotes: 1

Related Questions