Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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;
}
}
Owner

rodrigokono commented Jun 11, 2012

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