C#lambda内连接最大值

时间:2016-05-22 04:45:12

标签: c# mysql linq lambda

我创建了这个sql查询,但很难将其转换为linq lambda。我对linq很新。

Select t1.* Fom msgs as t1
Inner join(
    Select fromUser, MAX(ts) as mts
    From msgs
    Where toUser='aUserName' AND isDeleted='0'
    Group By fromUser
)t2 On (t2.fromUser=t1.fromUser and t1.ts = t2.mts) Order By ts desc;

1 个答案:

答案 0 :(得分:1)

您可以使用OrderByDescending(linq扩展名)和GroupBy实现相同的目标。

var messages = msg.ToList();
var results = messages.Where(x=> x.toUser = "aUserName" AND isDeleted="0")
    .GroupBy(x=>x.fromUser)
    .Select(x=>
     { 
         var maxitem = x.OrderByDescending(y=>y.ts).First();
         return new 
         {
              fromUser = maxItem.fromUser,
              ts = maxitem.ts,
              ... // remaining properties.
         }
     })
    .ToList();