Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max date record in LINQ

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(); 
like image 628
Salah Sanjabian Avatar asked Feb 04 '12 18:02

Salah Sanjabian


People also ask

How to get max date in LINQ query?

SelectMany(g=> g. Max(r=>. Field<datetime>("Date")) //item in group with max time . Select(r=> new { ID = r.


2 Answers

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)

like image 53
Kirill Polishchuk Avatar answered Sep 20 '22 04:09

Kirill Polishchuk


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(); 
like image 29
BrokenGlass Avatar answered Sep 20 '22 04:09

BrokenGlass