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.
Next in Data Shaping & LINQ: Parse Filters
Input: 25 items, page = 2, pageSize = 10
Output: items 11-20, total count 25, total pages 3
I would normalize page and page size first, then compute total count and total pages. The skip amount is (page - 1) * pageSize. If the page is beyond the end, Skip and Take naturally return an empty list. I would mention that this helper is for in-memory lists; database paging should apply Skip and Take before materializing.
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 pageItems = items
.Skip((page - 1) * pageSize)
.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.
Spot a weak answer, missing edge case, or clearer explanation? Send it in.