Update your secret recipe...
<p>How to implement a generic paginated result service in C#</p> <p>Create a <code>PagedResult</code> DTO</p> <pre><code class="language-cs">public class PagedResult<T> { public List<T> Items { get; set; } public int TotalCount { get; set; } public int PageSize { get; set; } public int CurrentPage { get; set; } public int TotalPages => (int)Math.Ceiling((double)TotalCount / PageSize); public PagedResult() { Items = []; } } </code></pre> <p>Create the <code>IPagedResultService</code> Interface</p> <pre><code class="language-cs">public interface IPagedResultService { Task<PagedResult<T>> GetPagedResultAsync<T>( IQueryable<T> query, int pageNumber, int pageSize) where T : class; } </code></pre> <p>Implement the <code>PagedResultService</code></p> <pre><code class="language-cs">public class PagedResultService : IPagedResultService { public async Task<PagedResult<T>> GetPagedResultAsync<T>( IQueryable<T> query, int pageNumber, int pageSize) 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; } } </code></pre> <p>Register the <code>PagedResultService</code> in <code>Program.cs</code></p> <pre><code class="language-cs">services.AddScoped<IPagedResultService, PagedResultService>(); </code></pre> <p>You can (and probably should) set a default value for pageNumber and pageSize at the highest level, eg at the controller level.</p>
Update Note
Back To All Notes