Created
June 11, 2012 00:33
-
-
Save rodrigokono/2907855 to your computer and use it in GitHub Desktop.
IQueryable Dynamic Expressions
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
public static class QueryableExtensions | |
{ | |
public static IQueryable<T> Filter<T>(this IQueryable<T> queryable, IEnumerable<KeyValuePair<string, string>> filters) where T : class | |
{ | |
foreach (var filter in filters) | |
{ | |
var propertyName = typeof(T).GetProperties().Select(x => x.Name).SingleOrDefault(x => x.ToLower() == filter.Key.ToLower()); | |
if (propertyName.IsNullOrWhiteSpace()) continue; | |
var parameterExpression = Expression.Parameter(typeof(T)); | |
var propertyExpression = Expression.Property(parameterExpression, propertyName); | |
var toStringCallExpression = Expression.Call(propertyExpression, typeof(T).GetMethod("ToString")); | |
var toLowerCallExpression = Expression.Call(toStringCallExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes)); | |
var constantExpression = Expression.Constant(filter.Value.ToLower()); | |
var equalExpression = Expression.Equal(toLowerCallExpression, constantExpression); | |
var methodCallExpression = Expression.Call(typeof(Queryable), "Where", new[] { typeof(T) }, queryable.Expression, Expression.Lambda<Func<T, bool>>(equalExpression, new[] { parameterExpression })); | |
queryable = queryable.Provider.CreateQuery(methodCallExpression) as IQueryable<T>; | |
} | |
return queryable; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var f = new Dictionary<string, string>()
f["Nome"] = "Rodrigo";
f["Sobrenome"] = "Kono"
var js = db.Pessoa.Filter(f);
O mesmo que:
var js = from p in db.Pessoa
where p.Nome == "Rodrigo"
where p.Sobrenome == "Kono"
select p;