EF Core translates the query to SQL and in SQL ORDER BY
cannot precede GROUP BY
.
Example:
SELECT *
FROM t
ORDER BY a
GROUP BY b
Oracle: SQL Error: ORA-00933: SQL command not properly ended (Line 4, Column 1)
SQL Server: Incorrect syntax near the keyword 'group'.
You can do this in LINQ-to-Objects, so. The documentation says:
The IGrouping<TKey,TElement> objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping<TKey,TElement>. Elements in a grouping are yielded in the order that the elements that produced them appear in source.
As @Ivan Stove points out: move OrderBy
before First()
:
List<User> query = await _context.Users
.GroupBy(s => s.GroupCode)
.OrderBy(g => g.Key)
.Take(10)
.Select(g => g.OrderByDescending(s => s.CreatedDateTime).First())
.ToList();
I also think that you need to order twice. Once to get the groups in the right order so that Take(10)
returns the first 10 GroupCode
s and another one to get the User in each group with the last CreatedDateTime
. Unless you need something else. But then please explain exactly what you need.