public static class QueryableExtensions { #region 内存分页 /// <summary> /// 返回对象分页列表 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="dataSource">已排序的数据源</param> /// <param name="pageIndex">页码,1开始</param> /// <param name="pageSize">页条数</param> /// <returns>对象分页列表</returns> public static IPagedList<T> ToPagedList<T>(this IList<T> dataSource, int pageIndex, int pageSize) where T : class { pageIndex = pageIndex <= 0 ? 1 : pageIndex; var pagedList = new PagedList<T> { PageIndex = pageIndex, PageSize = pageSize, TotalCount = dataSource.Count, Entities = dataSource.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList() }; return pagedList; } /// <summary> /// 返回对象分页列表 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="dataSource">已排序的数据源</param> /// <param name="pager">分页器对象;当为空时,分页器取默认值</param> /// <returns>对象分页列表</returns> public static IPagedList<T> ToPagedList<T>(this IList<T> dataSource, Pager pager) where T : class { pager = pager ?? new Pager(); return dataSource.ToPagedList(pager.PageIndex, pager.PageSize); } #endregion #region IQueryable分页 /// <summary> /// 返回对象分页列表 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="dataSource">已排序的数据源</param> /// <param name="pageIndex">页码,1开始</param> /// <param name="pageSize">页条数</param> /// <returns>对象分页列表</returns> public static IPagedList<T> ToPagedList<T>(this IQueryable<T> dataSource, int pageIndex, int pageSize) where T : class { pageIndex = pageIndex <= 0 ? 1 : pageIndex; var pagedList = new PagedList<T> { PageIndex = pageIndex, PageSize = pageSize, TotalCount = dataSource.Count(), Entities = dataSource.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList() }; return pagedList; } /// <summary> /// 返回对象分页列表 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="dataSource">已排序的数据源</param> /// <param name="pager">分页器对象;当为空时,分页器取默认值</param> /// <returns>对象分页列表</returns> public static IPagedList<T> ToPagedList<T>(this IQueryable<T> dataSource, Pager pager) where T : class { pager = pager ?? new Pager(); return dataSource.ToPagedList(pager.PageIndex, pager.PageSize); } #endregion /// <summary> /// 当满足特定条件时执行查询 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="source">查询对象</param> /// <param name="condition">需要满足的条件</param> /// <param name="predicate">满足条件时执行的查询表达式</param> /// <returns>结果集</returns> public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool condition, Expression<Func<T, bool>> predicate) { return condition ? source.Where(predicate) : source; } }
/// <summary> /// 分页器 /// </summary> public class Pager { /// <summary> /// 分页索引(默认为1) /// </summary> public int PageIndex { get; set; } = 1; /// <summary> /// 分页大小(默认为10) /// </summary> public int PageSize { get; set; } = 10; }