我正在尝试为EF创建一个Linq查询,该查询连接来自内部选择的2个值。在下面你会发现执行这个技巧的SQL查询,在Linq中尝试这样做时会更加棘手。
我使用POCO对象并希望查询返回List而不是匿名类型。这对Linq到EF有可能吗?
SELECT s1.* FROM [Statistics] s1 INNER JOIN ( SELECT MAX(CreateDate) as createdate FROM [Statistics] GROUP BY UserId ) s2 ON s1.UserId = s2.[UserId] and s1.CreateDate = s2.createdate ORDER BY s1.Balance desc
答案 0 :(得分:2)
您可以使用Where或Join执行此操作。
from s1 in Statistics
join s2 in (from s in Statistics group s by s.UserId into g
select new { UserId = g.Key, CreateDate = g.Max (s => s.CreateDate) })
on new { s1.UserId, s1.CreateDate } equals new { s2.UserId, s2.CreateDate }
orderby s1.Balance descending
select s1;
或者,
from s1 in Statistics
from s2 in (from s in Statistics group s by s.UserId into g
select new { UserId = g.Key, CreateDate = g.Max (s => s.CreateDate) })
where s1.UserId == s2.UserId && s1.CreateDate == s2.CreateDate
orderby s1.Balance descending
select s1;