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
});
if you always have at least a joining row, sort t3 by timestamp and fetch the first one (should be the greatest value).