0

I have this property in a class

public Expression<Func<T, string, bool>> FilterExp { get; set; }

I need to replace the string paramater with a value that is known at runtime and covert in into this:

Expression<Func<T, bool>>

so I can use it with IQueryable.

This is what it looks like when I set the filter:

PagingProvider<Employee> provider = new PagingProvider<Employee>(context.Employees);
provider.FilterExp = (employee, filterText) => employee.FullName.Contains(filterText);
return provider.GetResults();

What would be the best way of changing the expression?

RoboDev
  • 4,003
  • 11
  • 42
  • 51

1 Answers1

1

I came up with this and it seems to be working:

protected class ParameterReplacer : ExpressionVisitor
{
    private ParameterExpression parameterExpression;
    private string newValue;

    public ParameterReplacer(ParameterExpression parameterExpression, string newValue)
    {
        this.parameterExpression = parameterExpression;
        this.newValue = newValue;
    }

    public override Expression Visit(Expression node)
    {
        if (node == parameterExpression)
            return Expression.Constant(this.newValue);

        return base.Visit(node);
    }
}

And in my code I use it like this:

var replacer = new ParameterReplacer(FilterExp.Parameters[1], Filter);
var newBody = replacer.Visit(FilterExp.Body);
var exp = Expression.Lambda<Func<T, bool>>(newBody, FilterExp.Parameters[0]);
return SourceData.Where(exp);
RoboDev
  • 4,003
  • 11
  • 42
  • 51