LINQ Interview Question #123

What is keyset pagination and how does LINQ express it?

LINQ Performance, EF Core LINQ, Expressions & Advanced Queries Senior Advanced

Quick Interview Answer

Keyset pagination retrieves the next page by filtering on the last value from the previous page using the same deterministic ordering. It avoids large Skip offsets.

Detailed Explanation

Keyset pagination retrieves the next page by filtering on the last value from the previous page using the same deterministic ordering. It avoids large Skip offsets.

The ordering key should be stable and usually unique, or multiple ordered values should be used to create a deterministic continuation condition.

Code Example

var nextPage = await db.Orders
    .Where(o => o.Id > lastOrderId)
    .OrderBy(o => o.Id)
    .Take(25)
    .ToListAsync();