简体   繁体   中英

Linq to Sql Query select last column

I have table like that

Id Count  Date
1   56    04.10.2012
2   41    05.10.2012
3   56    06.10.2012

I have only single new record per one day with Count updated during the day

I need to select the latest record using Linq to Sql

var result = from q in repositoryManager.Repository.AsQueryable<Detail>()
             group q by q.Id
             into grp
             select grp.OrderByDescending(x => x.Id).FirstOrDefault();

the query above does not working it is returning first row instead o last. How to fix that?

You don't need to group by since you are not aggregating anything. Try this:

var result = repositoryManager.Repository.OrderByDescending(x => x.Id).FirstOrDefault();

The reason your method didn't work is because you were ordering each group (and each group only had one record), not the groups themselves. You don't need groups in the first place when you don't need to aggregate data based on the column you are grouping by.

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