在开发一个项目过程中,出现需要对搜索结果进行分页的需求,实现过程记录如下
1. 首先我们需要有一个分页类PaginatedList<TEntity>, 这个分页类大概包括以下信息
总行数,当前页面,每页行数,总页数, 前一页,下一页. 为了方便后面操作,我们使它继承自List<T>
写成如下:
public class PaginatedList<TEntity> : List<TEntity> { public int PageIndex { get; private set; } public int PageSize { get; private set; } public int TotalCount { get; private set; } public int TotalPageCount { get; private set; } public bool HasPreviousPage => (PageIndex > 1); public bool HasNextPage { get { return (PageIndex < TotalPageCount); } } public PaginatedList() { } public PaginatedList(IEnumerable<TEntity> source, int pageIndex, int pageSize, int totalCount) : this() { if (source == null) { throw new ArgumentNullException("source"); } AddRange(source); PageIndex = pageIndex; PageSize = pageSize; TotalCount = totalCount; TotalPageCount = (int)Math.Ceiling(totalCount / (double)pageSize); } }