EF Core Groupby获得最高行数

时间:2017-12-29 08:50:01

标签: c# linq-to-entities .net-core asp.net-core-webapi ef-core-2.0

我有下表:

| 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),我可以在每组Version中选择最高ParentId

我目前有这样的事情:

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

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

1 个答案:

答案 0 :(得分:1)

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

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