OrderBy sorts LINQ query results by a selected key. With Entity Framework Core, it can delegate sorting to the database instead of loading every record for programmatic sorting. section 5.4.2
Practical considerations:
- The standard EF Core overload expects a lambda expression, such as b => b.Name. section 5.4.2
- A switch can map client-provided column names to explicit OrderBy expressions, but each sortable column needs its own case. section 5.4.2
- System.Linq.Dynamic.Core enables string-based ordering, allowing a request value such as sortColumn to reach OrderBy directly. section 5.4.2
Listing 5.7 BoardGameController.Get() method (with paging and sorting)
[HttpGet(Name = "GetBoardGames")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 60)]
public async Task<RestDTO<BoardGame[]>> Get(
int pageIndex = 0,
int pageSize = 10,
string? sortColumn = "Name")
{
var query = _context.BoardGames
.OrderBy(sortColumn)
.Skip(pageIndex * pageSize)
.Take(pageSize);
return new RestDTO<BoardGame[]>()
{
Data = await query.ToArrayAsync(),
PageIndex = pageIndex,
PageSize = pageSize,
RecordCount = await _context.BoardGames.CountAsync(),
Links = new List<LinkDTO> {
new LinkDTO(
Url.Action(
null,
"BoardGames",
new { pageIndex, pageSize },
Request.Scheme)!,
"self",
"GET"),
}
};
}
Shows OrderBy integrated with paging, asynchronous materialization, a default sort column, and an API response. section 5.4.2
