using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace Oyang.Tool { public class QueryableHelper { public static IQueryableWhereIf (IQueryable source, bool isTrue, Expression bool>> predicate) { if (isTrue) { source = source.Provider.CreateQuery ( Expression.Call( null, Where_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); } return source; } private static MethodInfo s_Where_TSource_2; private static MethodInfo Where_TSource_2(Type TSource) => (s_Where_TSource_2 ?? (s_Where_TSource_2 = new Func object>, Expression object, bool>>, IQueryable<object>>(Queryable.Where).GetMethodInfo().GetGenericMethodDefinition())) .MakeGenericMethod(TSource); public static List ToPageList (IQueryable source, ref int pageIndex, int pageSize, string sortField, bool isAsc, out int totalCount) { totalCount = source.Count(); int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1; if (pageCount > 0 && pageIndex > pageCount) { pageIndex = pageCount; } var param = Expression.Parameter(typeof(TSource)); var body = Expression.Property(param, sortField); dynamic keySelector = Expression.Lambda(body, param); source = isAsc ? Queryable.OrderBy(source, keySelector) : Queryable.OrderByDescending(source, keySelector); source = source.Skip((pageIndex - 1) * pageSize).Take(pageSize); return source.ToList(); } public static List ToPageList (IQueryable source, IPagination p) { int pageIndex = p.PageIndex; List temp = ToPageList (source, ref pageIndex, p.PageSize, p.SortField, p.IsAsc, out int totalCount); p.TotalCount = totalCount; p.PageIndex = pageIndex; return temp; } } }