Skip to content

Instantly share code, notes, and snippets.

@Bartmax
Last active February 12, 2016 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bartmax/5a55ff88413174d49301 to your computer and use it in GitHub Desktop.
Save Bartmax/5a55ff88413174d49301 to your computer and use it in GitHub Desktop.
PaginatedList<T>
public static class IQueryableExtensions
{
public async static Task<PagedItems<T>> ToPagedItemsAsync<T>(this IQueryable<T> source, int pageSize, int pageIndex = 1)
{
var count = await source.CountAsync().ConfigureAwait(false);
var collection = await source
.Skip((pageIndex - 1) * pageSize)
.Take(pageSize)
.ToListAsync().ConfigureAwait(false);
return new PagedItems<T>(collection, count, pageSize, pageIndex);
}
}
public class PagedItems<T> : IEnumerable<T>
{
private IEnumerable<T> items;
public PagedItems(IEnumerable<T> items, int totalCount, int pageSize, int pageIndex)
{
if (pageIndex < 1) throw new ArgumentOutOfRangeException(nameof(PageIndex));
if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(PageSize));
this.items = items;
TotalCount = totalCount;
PageSize = pageSize;
PageIndex = pageIndex;
}
public int PageIndex { get;}
public int PageSize { get; }
public int TotalCount { get; }
public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
public bool HasPreviousPage => PageIndex > 1;
public bool HasNextPage => PageIndex < TotalPages;
public IEnumerator<T> GetEnumerator() => items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment