EF如何分页最大优化

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,
    }

 

上一篇:DataGridView分页功能的实现


下一篇:SSM,AJAX,PageHelper,Layui实现分页功能