max date record in LINQ max date record in LINQ sql-server sql-server

max date record in LINQ


Starting from .NET 6 MaxBy LINQ method is available.


Prior to .NET 6:

O(n log n):

var result = items.OrderByDescending(i => i.Date).First();

O(n) – but iterates over the sequence twice:

var max = items.Max(i => i.Date);var result = items.First(i => i.Date == max);

Or you can use MoreLINQ which has MaxBy method which is O(n)


To get the maximum Sample value by date without having to sort (which is not really necessary to just get the maximum):

var maxSample  = Samples.Where(s => s.Date == Samples.Max(x => x.Date))                        .FirstOrDefault();


var lastInstDate = model.Max(i=>i.ScheduleDate);

We can get max date from the model like this.