public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName, bool desc = false)
{
ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
propertyName = typeof(T).GetProperties().Where(p => p.Name.ToLower() == propertyName.ToLower()).First().Name;
MemberExpression property = Expression.Property(parameter, propertyName);
LambdaExpression lambda = Expression.Lambda(property, parameter);
string methodName = (desc) ? "OrderBy" : "OrderByDescending";
MethodCallExpression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
new Type[] { source.ElementType, property.Type },
source.Expression, Expression.Quote(lambda));
return source.Provider.CreateQuery<T>(methodCallExpression);
}
public static IQueryable<T> Filter<T>(this IQueryable<T> source, Filters flr)
{
ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
var property = Expression.Property(parameter, source.ElementType.GetProperty(flr.Field));
var keyword = flr.Value.ToLower();
var CONTAINS_METHOD = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var TO_LOWER_METHOD = typeof(string).GetMethod("ToLower", new Type[] { });
var toLowerExpression = Expression.Call(property, TO_LOWER_METHOD);
var termConstant = Expression.Constant(keyword, typeof(string));
var containsExpression = Expression.Call(toLowerExpression, CONTAINS_METHOD, termConstant);
var predicate = Expression.Lambda<Func<T, bool>>(containsExpression, parameter);
Expression methodCallExpression = Expression.Call(typeof(Queryable), "Where",
new Type[] { source.ElementType },
source.Expression, Expression.Quote(predicate));
return source.Provider.CreateQuery<T>(methodCallExpression);
}
public static IQueryable<T> KendoGrid<T>(this IQueryable<T> source, GridOptions gridOptions, string defaultSort = "")
{
if (gridOptions.Sort != null && gridOptions.Sort.Count() > 0)
{
source = source.SortBy<T>(gridOptions.Sort.First().Field, gridOptions.Sort.First().IsDesc);
}
else if(!string.IsNullOrWhiteSpace(defaultSort))
{
source = source.SortBy<T>(defaultSort, true);
}
if (gridOptions.Skip > 0)
{
source = source.Skip(gridOptions.Skip);
}
if (gridOptions.Take > 0)
{
source = source.Take(gridOptions.Take);
}
if (gridOptions.Filter != null)
{
switch (gridOptions.Filter.Logic)
{
case "and":
foreach (var flr in gridOptions.Filter.Filters)
{
source = source.Filter<T>(flr);
}
break;
}
}
return source;
}
}
}
Add Expression to IQueryable
最新推荐文章于 2021-10-13 14:43:29 发布