IQueryable简单分页的扩展方法


IQueryable简单分页的扩展方法 ,废话不多说,直接上干货!

/// 
    /// 分页列表
    /// 
    public class Page
    {
        public Page()
        {

        }
        public Page(List items, int pageIndex, int pageSize, int totalCount)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            Total = totalCount;
            PageTotal = (int)Math.Ceiling(totalCount / (double)pageSize);
            Items = items;
        }

        /// 
        /// 当前页码
        /// 
        public int PageIndex { get; set; }

        /// 
        /// 每页记录数
        /// 
        public int PageSize { get; set; }

        /// 
        /// 总记录数
        /// 
        public int Total { get; set; }

        /// 
        /// 总页数
        /// 
        public int PageTotal { get; set; }

        /// 
        /// 分页数据
        /// 
        public List Items { get; set; }
    }
public static class PagedListExtensions
    {
        /// 
        /// PagedList
        /// 
        /// 
        /// 1为起始页
        /// 
        /// 
        public static async Task> ToPagedListAsync(
            this IQueryable query,
            int pageIndex,
            int pageSize,
            CancellationToken cancellationToken = default)
        {
            if (pageIndex < 1) throw new ArgumentOutOfRangeException(nameof(pageIndex));
            int realIndex = pageIndex - 1;
            int count = await query.CountAsync(cancellationToken).ConfigureAwait(false);
            var items = await query.Skip(realIndex * pageSize)
                                   .Take(pageSize)
                                   .ToListAsync(cancellationToken)
                                   .ConfigureAwait(false);
            return new Page(items, pageIndex, pageSize, count);
        }

        public static Page ToPagedList(
            this IQueryable query,
            int pageIndex,
            int pageSize)
        {
            if (pageIndex < 1) throw new ArgumentOutOfRangeException(nameof(pageIndex));
            int realIndex = pageIndex - 1;
            int count = query.Count();
            var items = query.Skip(realIndex * pageSize)
                             .Take(pageSize)
                             .ToList();
            return new Page(items, pageIndex, pageSize, count);
        }
    }