开发者

Query grouped entity with max value

开发者 https://www.devze.com 2023-03-26 03:50 出处:网络
I have an enti开发者_StackOverflow中文版ty 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

I have an enti开发者_StackOverflow中文版ty 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?


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消