简体   繁体   中英

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!

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){}
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM