3

我正在尝试为 EF 创建一个 Linq 查询,该查询连接来自内部选择的 2 个值。在下面,您会发现可以解决问题的 SQL 查询,在 Linq 中尝试这样做时,事情会变得更加棘手。

我使用 POCO 对象并希望查询返回 List 而不是匿名类型。Linq to EF 有可能吗?

选择 s1.*
FROM [统计] s1
内部联接
(
    选择 MAX(CreateDate) 作为 createdate
    来自[统计]
    按用户 ID 分组
) s2
ON s1.UserId = s2.[UserId] 和 s1.CreateDate = s2.createdate
ORDER BY s1.Balance desc
4

1 回答 1

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;
于 2012-04-16T17:57:06.017 回答