A Simple Pagination Helper With Metadata

ebeeraheem

View Profile
119 views
Sep 29, 2025
Updated Dec 30, 2025

Create a PagedResult class

public class PagedResult<T>
{
    public IEnumerable<T> Items { get; set; } = [];
    public string? SearchTerm { get; set; }
    public int TotalCount { get; set; }
    public int StartRecord => (CurrentPage - 1) * PageSize + 1;
    public int EndRecord => Math.Min(StartRecord + PageSize - 1, TotalCount);
    public int CurrentPage { get; set; }
    public int PageSize { get; set; }
    public int TotalPages => (int)Math.Ceiling((double)TotalCount / PageSize);
    public bool HasPreviousPage => CurrentPage > 1;
    public bool HasNextPage => CurrentPage < TotalPages;

    public static PagedResult<T> Empty(int PageNumber, int PageSize)
    {
        return new PagedResult<T>
        {
            CurrentPage = PageNumber,
            PageSize = PageSize,
            TotalCount = 0,
            Items = []
        };
    }
}

Create the pagination helper class with the pagination method

public static class Pagination
{
   public static async Task<PagedResult<T>> PaginateAsync<T>(
       this IQueryable<T> query,
       int pageNumber = 1,
       int pageSize = 10)
       where T : class
   {
       var result = new PagedResult<T>
       {
           CurrentPage = pageNumber,
           PageSize = pageSize,
           TotalCount = await query.CountAsync(),
           Items = await query
           .Skip((pageNumber - 1) * pageSize)
           .Take(pageSize)
           .ToListAsync()
       };
       return result;
   }
}

Then you use it as such (assuming you've already filtered and sorted your data)

var response = await query.PaginateAsync(pageNumber, pageSize);

Easy peasy.