在项目中用到一个通用的分页类,感觉很好用,分享一下,直接来代码:
//----------------------------------------------------------------------- // <copyright file="StandardPageResult" company="FenSiShengHuo, Ltd."> // Copyright (c) 2018 , All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace DotNet.MVC.Infrastructure.Paging { /// <summary> /// 分页结果实体 /// </summary> public class PageResult { /// <summary> /// 状态 /// </summary> public bool Status { get; set; } = true; /// <summary> /// 消息 /// </summary> public string StatusMessage { get; set; } /// <summary> /// 当前页 /// </summary> public int PageIndex { get; set; } /// <summary> /// 每页大小 /// </summary> public int PageSize { get; set; } /// <summary> /// 总数据量 /// </summary> public int TotalCount { get; set; } /// <summary> /// 总页数 /// </summary> public int TotalPages { get; set; } /// <summary> /// 有没有前一页 /// </summary> public bool HasPreviousPage => (PageIndex > 0); /// <summary> /// 有没有下一页 /// </summary> public bool HasNextPage => (PageIndex + 1 < TotalPages); } /// <summary> /// 分页数据 /// </summary> /// <typeparam name="T"></typeparam> public class PageResult<T> : PageResult { public T Value { get; set; } public PageResult() { } /// <summary> /// source 从数据库查询出来的就是分页的结果 /// </summary> /// <param name="source"></param> /// <param name="request"></param> /// <param name="totalCount"></param> public PageResult(T source, PageRequest request, int totalCount) : this() { if (request.PageSize == 0) { return; } TotalCount = totalCount; TotalPages = TotalCount / request.PageSize; if (TotalCount % request.PageSize > 0) TotalPages++; this.PageSize = request.PageSize; this.PageIndex = request.PageIndex; this.Value = source; } } } /// <summary> /// 分页扩展方法 /// </summary> namespace DotNet.MVC.Infrastructure.Paging { public static class PageResultExtension { /// <summary> /// 分页扩展 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="request"></param> /// <param name="totalCount"></param> /// <returns></returns> public static PageResult<T> ToPageResult<T>(this T source, PageRequest request, int totalCount) { return new PageResult<T>(source, request, totalCount); } } }
使用方法参考
WechatAccountSettingManager manager = new WechatAccountSettingManager(); DataTable dt = manager.GetDataTableByPage(out recordCount, pager.PageIndex, pager.PageSize, conditions, manager.DbHelper.MakeParameters(dbParameters), pager.Sort + " " + pager.SortDirection); List<WechatAccountSettingEntity> list = BaseEntity.GetList<WechatAccountSettingEntity>(dt); PageResult<List<WechatAccountSettingEntity>> result = list.ToPageResult(pager, recordCount);
这个分页可以对后台任意对象进行输出,包括List<T>,IList<T>,DataTable等任意集合对象