Linq: Select Most Recent Record of Each Group

血红的双手。 提交于 2019-12-25 20:05:08

问题


I want to get the latest record of each group from a SQL Server table using Linq.

Table Example:

I want to get this result:

My Linq query returns one record for each company, but it doesn't return the most recent ones:

var query = from p in db.Payments
            where p.Status == false 
            && DateTime.Compare(DateTime.Now, p.NextPaymentDate.Value) == 1
            group p by p.CompanyID into op                                          
            select op.OrderByDescending(nd => nd.NextPaymentDate.Value).FirstOrDefault();

What am i missing here? Why isn't the NextPaymentDate being ordered correctly?

!!UPDATE!! My query is working as expected. After analysing @Gilang and @JonSkeet comments i ran further tests and found that i wasn't getting the intended results due to a column that wasn't being updated.


回答1:


 var query = from p in db.Payments
             where p.Status == false
             group p by p.CompanyID into op
             select new { 
                 CompanyID = op.Key,
                 NextPaymentDate = op.Max(x => x.NextPaymentDate), 
                 Status = false
             };

The reason your query is not being ordered correctly is that your query does not do proper grouping. You did correctly grouping by CompanyID, but then you have to retrieve the maximum NextPaymentDate by calling aggregate function.

Status can be assigned false because it is already filtered by Where clause in the early clauses.



来源:https://stackoverflow.com/questions/33685630/linq-select-most-recent-record-of-each-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!