LINQ Interview Question #97

How do Skip and Take support pagination?

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

Quick Interview Answer

Skip ignores a specified number of elements, while Take returns a specified number of following elements. Together they can implement offset-based pagination.

Detailed Explanation

Skip ignores a specified number of elements, while Take returns a specified number of following elements. Together they can implement offset-based pagination.

A deterministic OrderBy should normally be applied before Skip and Take, particularly for database queries, so page boundaries are predictable.

Code Example

int page = 3;
int pageSize = 20;

var items = await db.Products
    .OrderBy(p => p.Id)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();