Sql内部连接选择语法到lambdas .join()语法
本文关键字:语法 join lambdas 连接 选择 Sql 内部 | 更新日期: 2023-09-27 18:08:46
我得到了这个查询:
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。
现在我想有这个查询在Lambdas语法为我的c#代码。
这可能吗?
编辑:
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
试着这样做:
var latestLogin = logins.Where(u => u.user == "userName").Max(u => u.logindate);
下面是一个使用Linq to object的测试。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();
}