I am trying to build an expression tree so that I can dynamically filter some data.
I came up with this, but it does not work on the line var lambda =
foreach (var rule in request.Where.Rules) { var parameterExpression = Expression.Parameter(typeof(string), rule.Field); var left = Expression.Call(parameterExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes)); var right = Expression.Constant(rule.Data.ToLower()); var method = typeof(string).GetMethod("Contains", new [] { typeof(string) }); var call = Expression.Call(left, method, right); var lambda = Expression.Lambda<Func<T, bool>>(call, parameterExpression); query = query.Where(lambda); }
Var rule has a field (ex "Name") that I want to compare with the text in rule.Data (ex 'tom'). Therefore, if T.Name.Contains("tom"); , I want the request to include a record, otherwise not.
var query has type IQueryable<T>
EDIT : he finally worked with this code:
foreach (var rule in request.Where.Rules) { var parameter = Expression.Parameter(typeof(T), "x"); var property = Expression.Property(parameter, rule.Field); var value = Expression.Constant(rule.Data); var type = value.Type; var containsmethod = type.GetMethod("Contains", new[] { typeof(string) }); var call = Expression.Call(property, containsmethod, value); var lambda = Expression.Lambda<Func<T, bool>>(call, parameter); query = query.Where(lambda); }
source share