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, }
标签:分页,pageSize,pageCount,Skip,EF,OrderByType,currentPage,优化,Desc 来源: https://www.cnblogs.com/330774495qq/p/12855455.html