Sql inner将一个select语法连接到lambdas .join()语法

时间:2013-04-12 14:31:02

标签: c# sql syntax lambda

我收到了这个问题:

select t.user
     , t.loginDate 
from t_login as t
inner join 
(
    select user, max(loginDate) as mostRecentLoginDate 
    from t_login 
    group by user
) as tt
    on t.user = tt.user 
   and t.loginDate = tt.mostRecentLoginDate ;

此查询效果很好,它为我的用户提供了最新的loginDate。

现在,我希望在我的C#代码中使用Lambdas语法进行此查询。

这可能吗?

编辑:

C#代码:

myApp.DataLayer dl = new myapp.DataLayer();
IQueryable<Logins> logins = dl.getAllLogins();

if(displayRecent)
{
    logins = logins.Where(p => p.LoginDate == logins.Where(pp => pp.User == p.User).Max(pp => pp.LoginDate));
}

foreach (Login login in logins) // here it crash with StackOverflow exception

2 个答案:

答案 0 :(得分:1)

尝试以下几点:

var latestLogin = logins.Where(u => u.user == "userName").Max(u => u.logindate);

答案 1 :(得分:0)

这是Linq对象的测试。它应该适用于Linq to SQL:

    public class Login { public DateTime loginDate { get; set; } public string user { get; set; } }

    [TestMethod()]
    public void foo()
    {
        var logins = new[] { 
          new Login() { loginDate = new DateTime(2013, 5, 1), user = "u1" }
        , new Login() { loginDate = new DateTime(2013, 5, 2), user = "u1" }
        , new Login() { loginDate = new DateTime(2013, 5, 3), user = "u2" }
        , new Login() { loginDate = new DateTime(2013, 5, 4), user = "u2" }

        };

        var lastLogins = logins.Where(l =>
                    l.loginDate == logins.Where(ll => ll.user == l.user)
                                         .Max(ll => ll.loginDate)
        ).ToList();
    }