Created
January 8, 2016 14:07
-
-
Save Sinstraliz/1c74ef794c65cb3742fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//x => x.fieldName.Contains(fieldValue) | |
public static IQueryable<T> FilterByValue<T>(this IQueryable<T> q, string fieldName, string fieldValue) | |
{ | |
try | |
{ | |
var param = Expression.Parameter(typeof(T), "p"); | |
var prop = Expression.Property(param, fieldName); | |
if (((PropertyInfo)prop.Member).PropertyType != typeof(string)) | |
return q; | |
var methodContains = typeof(string).GetMethod("Contains", new[] { typeof(string) }); | |
Expression e1 = Expression.Call(prop, methodContains, Expression.Constant(fieldValue)); | |
var exp = Expression.Lambda<Func<T, bool>>(e1, param); | |
var mce = Expression.Call(typeof(Queryable), "Where", new Type[] { q.ElementType }, q.Expression, exp); | |
return q.Provider.CreateQuery<T>(mce); | |
} | |
catch (Exception ex) | |
{ | |
return q; | |
} | |
} | |
public static IQueryable<T> FilterByValue<T>(this ObjectQuery<T> q, string fieldName, string fieldValue) | |
{ | |
return FilterByValue<T>(q.AsQueryable<T>(), fieldName, fieldValue); | |
} | |
public static IQueryable<T> OrderByField<T>(this IQueryable<T> queryable, string sortField, bool ascending) | |
{ | |
try | |
{ | |
var param = Expression.Parameter(typeof(T), "p"); | |
var prop = Expression.Property(param, sortField); | |
var exp = Expression.Lambda(prop, param); | |
var method = ascending ? "OrderBy" : "OrderByDescending"; | |
var types = new Type[] { queryable.ElementType, exp.Body.Type }; | |
var mce = Expression.Call(typeof(Queryable), method, types, queryable.Expression, exp); | |
return queryable.Provider.CreateQuery<T>(mce); | |
} | |
catch (Exception ex) | |
{ | |
return queryable; | |
} | |
} | |
public static IEnumerable<T> OrderByField<T>(this IEnumerable<T> enumerable, string sortField, bool ascending) | |
{ | |
return OrderByField<T>(enumerable.AsQueryable<T>(), sortField, ascending); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment