max date record in LINQ
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();
Starting from .NET 6 MaxBy
LINQ method is available.
var result = items.MaxBy(i => i.Date);
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)