简体   繁体   English

在LINQ查询联接中查找MAX日期

[英]Finding MAX date in LINQ query join

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. 请原谅我对此问题的知识不足,因为它很基本,但是我有一个空的 [DateTime]列,我想使用LINQ查询为每个用户选择记录,该记录的最大“时间戳”是通过一个联接。

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
                });

if you always have at least a joining row, sort t3 by timestamp and fetch the first one (should be the greatest value). 如果您始终至少有一个连接行,则按时间戳排序t3并获取第一个(应为最大值)。

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))
            .OrderBy(u => u.timestamp).First()           // <--------- add this
            where myBusinessUnits.Contains(t1.BusinessUnit_ID)
            orderby (t2.Name) descending
            select new GlobalMyTeamDetailModel
            {
                 LastLogin = t3.timestamp,
                 Name = t2.Name

            });

use group by and max in linq like below 在linq中使用group by和max,如下所示

 From p In db.Products _
            Group p By p.CategoryID Into g = Group _
            Select New With {g, .MaxPrice = g.Max(Function(p) p.UnitPrice)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM