namespace Entity
{
public interface IPagedList
{
/// <summary>
/// 記錄數
/// </summary>
int TotalCount { get; set; }
/// 頁數
int TotalPages { get; set; }
/// 目前頁
int PageIndex { get; set; }
/// 頁面大小
int PageSize { get; set; }
/// 是否上一頁
bool IsPreviousPage { get; }
/// 是否下一頁
bool IsNextPage { get; }
}
/// <summary>
/// 分頁通用類
/// </summary>
/// <typeparam name="T"></typeparam>
public class PagedList<T> : List<T>, IPagedList
/// 資料源為IQueryable的範型
/// <param name="source">資料源</param>
/// <param name="index">目前頁</param>
/// <param name="pageSize">每頁顯示多少條記錄</param>
public PagedList(IQueryable<T> source, int index, int pageSize)
{
if (source != null) //判斷傳過來的實體集是否為空
{
int total = source.Count();
this.TotalCount = total;
this.TotalPages = total / pageSize;
if (total % pageSize > 0)
TotalPages++;
this.PageSize = pageSize;
if (index > this.TotalPages)
{
index = this.TotalPages;
}
if (index < 1)
index = 1;
this.PageIndex = index;
this.AddRange(source.Skip((index - 1) * pageSize).Take(pageSize).ToList()); //Skip是跳到第幾頁,Take傳回多少條
}
}
/// 總頁數
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; } }
private NameValueCollection _AddParameters = new NameValueCollection();
/// 分頁參數
public NameValueCollection AddParameters
get { return _AddParameters; }
set { _AddParameters = value; }
/// PagedList擴充類
public static class ExtendPagedList
/// 傳回PagedList<T>類型的IQueryable的擴充方法
/// <typeparam name="T"></typeparam>
/// <param name="linq"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public static PagedList<T> ToPagedList<T>(this IQueryable<T> linq, int pageIndex, int pageSize)
return new PagedList<T>(linq, pageIndex, pageSize);
}