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

时间:2011-10-20 12:49:23

标签: c# linq asp.net-mvc-3 linq-to-sql

请原谅我对此问题缺乏了解,因为这个问题非常基础,但我有一个可以 [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
                });

2 个答案:

答案 0 :(得分:1)

如果你总是至少有一个连接行,按时间戳排序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

            });

答案 1 :(得分:0)

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