Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return record with max column value using Entity Framework 6

Trying to get record with max datetime value for ReceivedDateTime column, however data set should be pre-filtered by some Id column (not unique). Solved this way:

using (var db = new SystemEntities())
{
    var records = db.Table.Where(p => p.Id == Id);
    var record = records.Where(p => p.ReceivedDateTime == records.Max(r => r.ReceivedDateTime)).FirstOrDefault();
    if(record != null)
    {

    }
}

Is there more beautiful, simpler and shorter implementation, notation? Thanks!

like image 943
Aleksey Kontsevich Avatar asked Jul 22 '26 14:07

Aleksey Kontsevich


2 Answers

You can simplify like the following using OrderByDescending:

using (var db = new SystemEntities())
{
    var record = db.Table.Where(p => p.Id == Id).OrderByDescending(x => x.ReceivedDateTime).FirstOrDefault();
    if(record != null){}
}
like image 57
OmG Avatar answered Jul 25 '26 04:07

OmG


Update

Between the time I opened the question and tried out a result, the original answer had been fixed. My apologies for not checking before I posted.

Update

Seeing as I cannot comment, I will post an answer on the side.

The above suggested var record = db.Table.Where(p => p.Id == Id).Max(x => x.ReceivedDateTime).FirstOrDefault() will not compile because Max will return for you a datetime.

You can do it using OrderByDescending they way you would in an SQL statement

// I used an in memory array but it should be the same.
var item = items.Where(x => x.Id == 2).OrderByDescending(x => x.ReceivedDate).FirstOrDefault();
like image 41
Fabulous Avatar answered Jul 25 '26 06:07

Fabulous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!