博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

EF如何分页最大优化

Posted on 2020-05-09 09:57  筑筑  阅读(392)  评论(0编辑  收藏  举报
public static class QueryableExtension
    {
        public static IQueryable<T> Paged<T>(this IQueryable<T> query, Expression<Func<T, object>> expression, OrderByType orderByType = OrderByType.Desc,int currentPage = 1, int pageSize = 5,int pageCount = 0)
        {
            if (currentPage < 1)
            {
                currentPage = 1;
            }
            var Skip = (currentPage - 1) * pageSize;
            var Take = pageSize;
            OrderByType byType = orderByType;

            var MaxPageIndex = pageCount % pageSize == 0 ? pageCount / pageSize : pageCount / pageSize + 1;

            if (currentPage > MaxPageIndex / 2)//页码大于一半用倒序
            {
                var Mod = pageCount % pageSize;
                var Page = (int)Math.Ceiling((Decimal)pageCount / pageSize);
                if (currentPage * pageSize >= pageCount)
                {
                    Skip = 0; Take = Mod == 0 ? pageSize : Mod;
                }
                else
                {
                    Skip = (Page - currentPage - 1) * pageSize + Mod;
                }
                byType = orderByType == OrderByType.Desc ? OrderByType.Asc : OrderByType.Desc;
            }
            else
            {
                byType = orderByType == OrderByType.Desc ? OrderByType.Desc : OrderByType.Asc;
            }
            if (pageCount > pageSize)
            {
                if (byType == OrderByType.Desc)
                    query = query.OrderByDescending(expression).Skip(Skip).Take(Take);
                else
                    query = query.OrderBy(expression).Skip(Skip).Take(Take);
            }
            return query;
        }
    }

    public enum OrderByType
    {
        Desc = 2,
        Asc = 1,
    }