简体   繁体   English

我如何选择组中的最后一行

[英]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. 我正在使用Linq查询来检索组。 Here is my LINQ query. 这是我的LINQ查询。

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. 使用FirstOfDefault()我正在获得组中的第一行。 Using LastOrDefault() I am getting run time exception. 使用LastOrDefault()我正在获得运行时异常。

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 . 这背后的原因是SQL语言没有SELECT BOTTOM语句,而是SELECT TOP语句。 Hence our LastOrDefault query could not be translated into SQL. 因此,我们的LastOrDefault查询无法转换为SQL。 The possible way of doing so is to OrderByDescending method. 这样做的可能方法是使用OrderByDescending方法。

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). 如果它是一个自动递增的数字值,则它可以是id字段,也可以是该行的添加日期(最好由服务器生成,否则可能会导致问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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