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 IQueryable<TSource> WhereIf<TSource>(IQueryable<TSource> source, bool isTrue, Expression<Func<TSource, bool>> predicate)
{
if (isTrue)
{
source = source.Provider.CreateQuery<TSource>(
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<IQueryable<object>, Expression<Func<object, bool>>, IQueryable<object>>(Queryable.Where).GetMethodInfo().GetGenericMethodDefinition()))
.MakeGenericMethod(TSource); public static List<TSource> ToPageList<TSource>(IQueryable<TSource> source, ref int pageIndex, int pageSize, string sortField, bool isAsc, out int totalCount)
{
totalCount = source.Count();
int pageCount = totalCount % pageSize == ? totalCount / pageSize : totalCount / pageSize + ;
if (pageCount > && 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 - ) * pageSize).Take(pageSize);
return source.ToList();
} public static List<TSource> ToPageList<TSource>(IQueryable<TSource> source, IPagination p)
{
int pageIndex = p.PageIndex;
List<TSource> temp = ToPageList<TSource>(source, ref pageIndex, p.PageSize, p.SortField, p.IsAsc, out int totalCount);
p.TotalCount = totalCount;
p.PageIndex = pageIndex;
return temp;
}
}
}
05-06 06:49