Мне легче справляться с нумерацией страниц, абстрагируясь от вопроса. Вот источник решения, которое я использую. Это сделает ваш код намного проще и превратит всю логику подкачки в один простой вызов ToPagedList(int index, int pageSize)
. Я не уверен на 100%, но я полагаю, что первоначально я получил этот источник от проекта Kona Роба Конери (его блог на http://blog.wekeroad.com/).
Класс помощника
public static class Pagination
{
public static PagedList<T> ToPagedList<T>(this IEnumerable<T> source, int index)
{
return new PagedList<T>(source.AsQueryable(), index, 10);
}
public static PagedList<T> ToPagedList<T>(this IEnumerable<T> source, int index, int pageSize)
{
return new PagedList<T>(source.AsQueryable(), index, pageSize);
}
public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index, int pageSize)
{
return new PagedList<T>(source, index, pageSize);
}
public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index)
{
return new PagedList<T>(source, index, 10);
}
}
Интерфейсы
public interface IPagedList<T> : IList<T>, IPagedList
{
}
public interface IPagedList
{
int TotalCount { get; set; }
int TotalPages { get; set; }
int PageIndex { get; set; }
int PageSize { get; set; }
bool IsPreviousPage { get; }
bool IsNextPage { get; }
}
Реализация PagedList
public class PagedList<T> : List<T>, IPagedList<T>
{
public PagedList(IQueryable<T> source, int index, int pageSize)
{
int total = source.Count();
this.TotalCount = total;
this.TotalPages = total/pageSize;
if (total%pageSize > 0)
TotalPages++;
this.PageSize = pageSize;
this.PageIndex = index;
this.AddRange(source.Skip(index*pageSize).Take(pageSize).ToList());
}
public PagedList(IEnumerable<T> source, int total, int index, int pageSize)
{
this.TotalCount = total;
this.TotalPages = total/pageSize;
if (total%pageSize > 0)
TotalPages++;
this.PageSize = pageSize;
this.PageIndex = index;
this.AddRange(source);
}
#region IPagedList<T> Members
public int TotalPages { get; set; }
public int TotalCount { get; set; }
public int PageIndex { get; set; }
public int PageSize { get; set; }
public bool IsPreviousPage
{
get { return (PageIndex > 0); }
}
public bool IsNextPage
{
get { return (PageIndex*PageSize) <= TotalCount; }
}
#endregion
}