Reputation: 3
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.
Upvotes: 0
Views: 294
Reputation: 7352
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).
Upvotes: 1