在 LINQ 查询连接中查找最大日期
请原谅我对这个问题缺乏了解,因为这个问题非常基本,但我有一个可为空 [DateTime] 列,我想使用 LINQ 查询为每个用户选择记录通过连接找到的最大“时间戳”。
这是我现在的疑问。
return (from t1 in db.BU
from t2 in db.UserNames
.Where(t => (t.User_Username == t1.Username))
from t3 in db.Logins
.Where(t => (t.username == t1.Username))
where myBusinessUnits.Contains(t1.BusinessUnit_ID)
orderby (t2.Name) descending
select new GlobalMyTeamDetailModel
{
LastLogin = t3.timestamp,
Name = t2.Name
});
如果有人能帮助我,我将不胜感激。
这是我试图为每个用户获取的“登录”表的最大值。
编辑:另一次尝试没有给出期望的结果:
var result =
(from t1 in db.LoginHistories
where t1.username == user
from t2 in db.UserNames
.Where(t => (t.User_Username == t1.username))
from t3 in db.UserBusinessUnits
.Where(t => (t.Username == t1.username))
where myBusinessUnits.Contains(t3.BusinessUnit_ID)
group t1 by new { t1.username } into g
let MaxDate = g.Max(uh => uh.timestamp)
select new GlobalMyTeamDetailModel
{
LastLogin = MaxDate,
Name = g.Key.username
});
Please excuse my lack of knowledge on this issue as this question as it's pretty basic, but I have a nullable [DateTime] column and I'd like to use a LINQ query to select records for each user with the maximum "Timestamp" found via a join.
Here's my query at the moment.
return (from t1 in db.BU
from t2 in db.UserNames
.Where(t => (t.User_Username == t1.Username))
from t3 in db.Logins
.Where(t => (t.username == t1.Username))
where myBusinessUnits.Contains(t1.BusinessUnit_ID)
orderby (t2.Name) descending
select new GlobalMyTeamDetailModel
{
LastLogin = t3.timestamp,
Name = t2.Name
});
If anybody could help me, I'd appreciate it.
It's the maximum value of the "Login" table I'm trying to get for each user.
EDIT: Another attempt which didn't give the desired result:
var result =
(from t1 in db.LoginHistories
where t1.username == user
from t2 in db.UserNames
.Where(t => (t.User_Username == t1.username))
from t3 in db.UserBusinessUnits
.Where(t => (t.Username == t1.username))
where myBusinessUnits.Contains(t3.BusinessUnit_ID)
group t1 by new { t1.username } into g
let MaxDate = g.Max(uh => uh.timestamp)
select new GlobalMyTeamDetailModel
{
LastLogin = MaxDate,
Name = g.Key.username
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您始终至少有一个连接行,请按时间戳对 t3 进行排序并获取第一个(应该是最大值)。
if you always have at least a joining row, sort t3 by timestamp and fetch the first one (should be the greatest value).
在 linq 中使用 group by 和 max 如下
use group by and max in linq like below