等效的LINQ to SQL查询

时间:2011-05-16 22:49:42

标签: linq-to-sql

任何人都可以帮我解决下面SQL的等效LINQ查询吗? 我是LINQ的新手

Select * From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1
group by SH1.StudentId)

这就是我试过的

var q = 
    from h in Students_History
    where h.Active=1
    group h by h.StudentId into g
    select new 
    {
        StudentID = g.Key,
        LatestModified = g.Max (x => x.ModifiedAt)
    }

这个linq查询没有给我正确的结果,并且某种程度上忽略了active = 1

我的Students_History表中有大约十几个字段,我希望所有这些字段不仅仅是studentId和ModifiedAt。

2 个答案:

答案 0 :(得分:0)

您需要使用 == 运算符进行比较。

答案 1 :(得分:0)

试试这个:

var q =
    from hg in Students_History
    group hg by hg.StudentId into g
    join h in Students_History on g.Key equals h.StudentId
    where h.Active == 1 && h.ModifiedAt == g.Max(x => x.ModifiedAt)
    select new
    {
        StudentID = h.StudentId,
        LatestModified = h.ModifiedAt
    }