liveBook · Manning

orderBy clause

As explained in Building Web APIs with ASP.NET Core

OrderBy is a LINQ query operator or extension method that orders query results by a specified key selector or ordering expression.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains lambda-based ordering, conditional column mapping, and Dynamic LINQ string ordering, stopping short of broader query-provider internals.
Examples
Demonstrates ordering BoardGame records by Name or Year and integrating sortColumn with paged controller results.
What it assumes
Assumes lambda expressions and EF Core query usage while introducing string-based dynamic ordering as an alternative.
What you can do after
Apply it via Entity Framework Core or System.Linq.Dynamic.Core to implement database-backed, client-selectable sorting.
How it connects
Connects OrderBy with LINQ, Entity Framework Core, Dynamic LINQ, database engines, and paging.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.