Skip to content

Instantly share code, notes, and snippets.

@rodrigokono
Created June 11, 2012 00:33
Show Gist options
  • Save rodrigokono/2907855 to your computer and use it in GitHub Desktop.
Save rodrigokono/2907855 to your computer and use it in GitHub Desktop.
IQueryable Dynamic Expressions
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;
}
}
@rodrigokono
Copy link
Author

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment