Last active
February 12, 2016 19:11
-
-
Save Bartmax/5a55ff88413174d49301 to your computer and use it in GitHub Desktop.
PaginatedList<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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