You need to group by UserId
and then order your groups by DateTime
property:
var result =(from s in db.Status
group s by s.UserId into g
let first=g.OrderByDescending(s=>s.DateTime).FirstOrDefault()
select new { userId= g.Key, Status= first.Status, CreatedDate=first.CreatedDate}).ToList();
Update
I tested my query using LinqPad, and it was translated to this lambda expression:
Status
.GroupBy (a => a.UserId)
.Select (
g =>
new
{
g = g,
first = g.OrderBy (a => a.DateTime).FirstOrDefault ()
}
)
.Select (
temp0 =>
new
{
Key = temp0.g.Key,
Status= temp0.first.Status,
CreatedDate=temp0.first.CreatedDate
}
)
Which is translated at the end to this SQL query:
SELECT [t1].[UserId] AS [UserId], (
SELECT [t3].[Status], [t3].[DateTime]
FROM (
SELECT TOP (1) [t2].[Status]
FROM [Status] AS [t2]
WHERE (([t1].[UserId] IS NULL) AND ([t2].[UserId] IS NULL)) OR (([t1].[UserId] IS NOT NULL) AND ([t2].[UserId] IS NOT NULL) AND ([t1].[UserId] = [t2].[UserId]))
ORDER BY [t2].[DateTime]
) AS [t3]
) AS [Status],(
SELECT [t5].[DateTime]
FROM (
SELECT TOP (1) [t4].[DateTime]
FROM [Application] AS [t4]
WHERE (([t1].[UserId] IS NULL) AND ([t4].[UserId] IS NULL)) OR (([t1].[UserId] IS NOT NULL) AND ([t4].[UserId] IS NOT NULL) AND ([t1].[UserId] = [t4].[UserId]))
ORDER BY [t4].[DateTime]
) AS [t5]
) AS [DateTime]
FROM (
SELECT [t0].[UserId]
FROM [Application] AS [t0]
GROUP BY [t0].[UserId]
) AS [t1]