Reputation: 25292
I have an entity BattleUser which contains four properties: Id, BattleId, UserId and DateTime. I need to query the last (by date) BattleUser entity for every user. So I came to something like this:
context.GroupBy(bu => bu.UserId, bu => bu).
Select(gbu => new { UserId = gbu.Key, DateTime = gbu.Max(bu => bu.DateTime) }).
ToList();
By this query I retrieve the last DateTime for each user. By using these values I can retrieve last BattleUser entities for every user by another query. Is there any way to modify initial query to solve the task by one query?
Upvotes: 1
Views: 236
Reputation: 177133
You can try this query:
context.GroupBy(bu => bu.UserId, bu => bu)
.Select(gbu => new
{
UserId = gbu.Key,
LastBattleUser = gbu.OrderByDescending(bu => bu.DateTime).FirstOrDefault()
})
.ToList();
Upvotes: 1