EF Core Groupby获得最高行数

问题描述 投票:1回答:1

我有下表:

| Id | ParentId | Version |
---------------------------
|  1 |    1     |    0    |
|  2 |    1     |    1    |
|  3 |    1     |    2    |
|  4 |    4     |    0    |
|  5 |    4     |    1    |
|  6 |    4     |    2    |

我正在寻找一个查询(pref Linq to EF),我可以在每组Versions中选择最高的ParentId

我目前有这样的事情:

await _context.Actions.GroupBy(a => a.ParentId)
                      .Select(s => s.Max(a => a.Version))
                      .ToListAsync();

我唯一的问题是只返回版本行,但我希望每组返回整行。

c# linq-to-entities .net-core asp.net-core-webapi ef-core-2.0
1个回答
1
投票

您需要通过降序排序并在每个组中取第一个

await _context.Actions
              .GroupBy(a => a.ParentId)
              .Select(s => s.OrderByDescending(a => a.Version).First())
              .ToListAsync();
© www.soinside.com 2019 - 2024. All rights reserved.