wasAsked.

Write LINQ code to implement pagination.

Altimetrik · Role not specified · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

Pagination uses Skip and Take after a stable OrderBy. Basic pagination public static IQueryable<T> Page<T>(this IQueryable<T> source, int pageNumber, int pageSize) => source.Skip((pageNumber - 1) * pageSize).Take(pageSize); Complete example with EF Core, returning metadata: public sealed record PagedResult<T>(IReadOnlyList<T> Items, int PageNumber, int PageSize, int TotalCount) { public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize); public bool HasNext => PageNumber < TotalPages; } public async Task<PagedResult<ProductDto>> GetProductsAsync(int page, int size, CancellationToken ct) { page = Math.Max(page, 1); size = Math.Clamp(size, 1, 100); // protect the API from huge pages var query = _db.Products.AsNoTracking() .Where(p => p.IsActive) .OrderBy(p => p.Name).ThenBy(p => p.Id); // stable, deterministic order var total = await query.CountAsync(ct); var items = await query .Skip((page - 1) * size) .Take(size) .Select(p => new ProductDto(p.Id, p.Name, p.Price)) .ToListAsync(ct); return new PagedResult<ProductDto>(items, page, size, total); } EF Core translates Skip and Take into SQL OFFSET ... ROWS FETCH NEXT ... ROWS ONLY (SQL Server) or LIMIT/OFFSET. Important points - Always OrderBy before Skip/Take; without a defined order, pages can repeat or skip rows (EF Core warns about this). Add a unique tie-breaker such as Id. - Validate page and size inputs. - Apply Skip/Take on IQueryable before ToList, so only one page is loaded from the database. - Use AsNoTracking and projection (Select) for read-only lists. In-memory pagination works the same way: list.Skip((page - 1) * size).Take(size). .NET 6 also added Chunk(size) to split a sequence into pages. Performance consideration Offset pagination gets slower on deep pages (the database must skip many rows), and counting the total on huge tables is expensive. For large or frequently changing data, use keyset (cursor) pagination: .Where(p => p.Id > lastSeenId).OrderBy(p => p.Id).Take(size) which uses an index seek and stays fast regardless of page depth.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics