Spaces:
Running
Running
File size: 1,420 Bytes
e908571 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | using Microsoft.EntityFrameworkCore;
using TaskTrackingSystem.Shared;
namespace TaskTrackingSystem.WebApi.Infrastructure;
public static class PaginationExtensions
{
public static int NormalizePage(int? page)
{
return page.HasValue && page.Value > 0 ? page.Value : 1;
}
public static async Task<PagedResult<T>> ToPagedResultAsync<T>(
this IQueryable<T> query,
int page,
int pageSize,
CancellationToken cancellationToken = default)
{
pageSize = NormalizePageSize(pageSize);
page = Math.Max(page, 1);
var totalCount = await query.CountAsync(cancellationToken);
var totalPages = totalCount == 0
? 0
: (int)Math.Ceiling(totalCount / (double)pageSize);
if (totalPages > 0 && page > totalPages)
{
page = totalPages;
}
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync(cancellationToken);
return new PagedResult<T>
{
Items = items,
TotalCount = totalCount,
Page = page,
PageSize = pageSize,
TotalPages = totalPages
};
}
public static int NormalizePageSize(int pageSize)
{
if (pageSize <= 0)
{
return 20;
}
return Math.Clamp(pageSize, 1, 100);
}
}
|