Home > Back-end >  Merge two collections, in case of duplicate elements pick the one with the latest date
Merge two collections, in case of duplicate elements pick the one with the latest date

Time:12-15

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.

CodePudding user response:

try

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