I have this table named sample with these values in MS Sql Server:
ID Date Description 1 2012/01/02 5:12:43 Desc1 2 2012/01/02 5:12:48 Desc2 3 2012/01/03 5:12:41 Desc3 4 2012/01/03 5:12:43 Desc4
Now I want to write LINQ query that result will be this:
4 2012/01/03 5:12:43 Desc4
I wrote this but it doesn't work:
List<Sample> q = (from n in Sample.Max(T=>T.Date)).ToList();
SelectMany(g=> g. Max(r=>. Field<datetime>("Date")) //item in group with max time . Select(r=> new { ID = r.
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)
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With