Interview question
Build a paged result from a list
Implements a safe in-memory paging helper with metadata and boundary handling.
TL;DR
Implements a safe in-memory paging helper with metadata and boundary handling.
Pagination math, bounds checking, Skip/Take, total count, and API-shaped DTOs.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement ToPage<T>(IReadOnlyList<T> items, int page, int pageSize). Page numbers are 1-based. Clamp invalid page and page size to safe defaults, and return items plus total count, page, page size, and total pages.
Input: 25 items, page = 2, pageSize = 10
Output: items 11-20, total count 25, total pages 3
I normalize page and page size first, then compute total count and total pages. I calculate the zero-based offset as long so an extreme page number cannot overflow before I compare it with the list length. If the offset is outside the list, the page is empty; otherwise I cast the already-bounded offset and slice the requested items. This helper is for an in-memory list—database paging belongs in the query before materialization.
public sealed record PagedResult<T>(
IReadOnlyList<T> Items,
int Page,
int PageSize,
int TotalCount,
int TotalPages);
public static PagedResult<T> ToPage<T>(IReadOnlyList<T>? items, int page, int pageSize)
{
items ??= Array.Empty<T>();
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize <= 0 ? 10 : pageSize, 1, 100);
var totalCount = items.Count;
var totalPages = totalCount == 0
? 0
: (int)Math.Ceiling(totalCount / (double)pageSize);
var offset = ((long)page - 1) * pageSize;
IReadOnlyList<T> pageItems = offset >= totalCount
? []
: items.Skip((int)offset).Take(pageSize).ToList();
return new PagedResult<T>(pageItems, page, pageSize, totalCount, totalPages);
}
For an in-memory list, Skip and Take are O(n) in the skipped amount for general enumerables, but with a list this is acceptable for helper-level usage. Space is O(pageSize) for the returned page.
int.MaxValue page without offset overflow.int.MaxValue as the page to prove offset calculation cannot wrap around.(page - 1) * pageSize overflow before Skip sees it.Next in Coding Practice: Parse Filters