选择最大日期和订单

时间:2016-01-05 11:12:48

标签: c# sql entity-framework linq

我有这个linq查询

var additivesTimesTamps = (from q in Uow.UserAdditionStamps.Data
                                       group q.UserId by new
                                       {
                                           q.UserId,
                                           q.TimeStamp
                                       } into qq
                                       select new
                                       {
                                           UID = qq.Key.UserId,
                                           TimeStamp = qq.Key.TimeStamp
                                       }).ToList();

并选择此项:

1   2013-01-31 18:08:19.847 
29  2013-01-04 16:28:52.557
29  2013-01-05 16:28:52.557

如何对每个UserId仅选择1个日期进行分组? t-sql就是这样:

select userid as uId, max([timestamp]) as ts 
from UserAdditionStamp 
group by UserId

这个t-sql代码正是我所需要的,但是在linq

1 个答案:

答案 0 :(得分:2)

您必须将groupby更改为仅在UserId上分组,然后为该组选择最大TimeStamp,如:

group q by  q.UserId into qq
                     select new
                     {
                         UID = qq.Key,
                         TimeStamp = qq.Max(x=>x.TimeStamp)
                     })