简体   繁体   中英

how can i select last row in a group

I have a problem getting last row in a each group. I am using Linq query to retrieve the groups. Here is my LINQ query.

return View(db.tblMsgs.OrderByDescending(a => a.Id)
    .GroupBy(a => new { a.Sender, a.Receiver }).Select(x => x.FirstOrDefault())
    .Where(a => a.Receiver == username).ToList());

using FirstOfDefault() I am getting first row in a group. Using LastOrDefault() I am getting run time exception.

That's what I run into too, in some time now.

After a little bit of research I found out that only way that works as it must is to reverse the list that you want the get the last item of and get the first item.

The reason behind this is that SQL languages does not have a statement as SELECT BOTTOM but SELECT TOP . Hence our LastOrDefault query could not be translated into SQL. The possible way of doing so is to OrderByDescending method.

return View(db.tblMsgs.OrderByDescending(a => a.Id)
    .GroupBy(a => new { a.Sender, a.Receiver }).Select(x => x.OrderByDescending(y => y.SomeAttribute).FirstOrDefault())
    .Where(a => a.Receiver == username).ToList());

Edit:

Only thing you should be choosy about is the column to order by. It can be the id field if it is an auto incremented number value, or an add date of the row(better be generated by server or it can cause problems).

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