LINQ Interview Question #98

Why is ordering important before Skip and Take?

Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate

Quick Interview Answer

Pagination requires a defined sequence order. Without deterministic ordering, a database is not required to return rows in a stable natural order, so records can appear on unexpected pages or move between requests.

Detailed Explanation

Pagination requires a defined sequence order. Without deterministic ordering, a database is not required to return rows in a stable natural order, so records can appear on unexpected pages or move between requests.

Order by a meaningful key and, when necessary, add a unique tie-breaker such as the primary key.

Code Example

var pageItems = await db.Orders
    .OrderByDescending(o => o.CreatedAt)
    .ThenByDescending(o => o.Id)
    .Skip(offset)
    .Take(pageSize)
    .ToListAsync();