简体   繁体   中英

using where clause after get last record?

using (EPOSEntities1 db = new EPOSEntities1())
{
    List<ActionPerformed> PLUlist = db.ActionPerformeds.ToList();
    ActionPerformed Latest_PLU = PLUlist.OrderByDescending(x => x.Date).FirstOrDefault();
}

This returns the last record stored. However I have now added another column in the table File_Name, how can I add a where clause to this to say orderByDescending to get the latest file, then from there get the first record with the file_Name as 'Sales'.??

so eg

    File_Name Date
12) Products 11/02/2014
13) Sales    11/02/2014
14) Products 11/02/2014

this would return record 13??

Use Where clause before OrderByDescending , if you call ToList it will cause immediate evaluation of the query and records will populated. It will be better if you call Where before evaluation.

ActionPerformed Latest_PLU = db.ActionPerformeds.Where(c=>File_Name == "Sales")
                             .OrderByDescending(x => x.Date)
                             .FirstOrDefault();

The Where method can filter your collection to only those items where the File_Name is "Sales" .

Consider placing your LINQ query before the executing call so that your LINQ-to-DB provider can perform the query server-side and only return you one item. What you were doing is bringing the entire ActionPeformeds table down from the server to the client, then performing the query client-side.

ActionPerformed Latest_PLU = db.ActionPerformeds
    .Where(x => x.File_Name == "Sales")
    .OrderByDescending(x => x.Date)
    .FirstOrDefault();

By "executing call" I mean ToList() , First() , FirstOrDefault() , etc.

ActionPerformed Latest_PLU = PLUlist.Where(p => p.File_Name == 'Sales').OrderByDescending(x => x.Date).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