I have this class:
public class CustomerFilter
{
public int Id { get; set; }
public int Name { get; set; }
}
And it is used like this:
public class Search
{
private Expression<Func<CustomerFilter, bool>> customerfilter;
public Expression<Func<CustomerFilter, bool>> CustomerFilter
{
set { customerfilter = value; }
}
}
var search = new Search();
search.CustomerFilter = (x => x.Id == 1);
From within the search class, how can I get the value of a property without using ExpressionVisitor
? Something like:
var customerId = customerFilter.Id; //Or something similar
If your CustomerFilter
only support MemberExpression==ConstantExpression
like in your sample code. Then you could get the information directly from the Expression
object.
var propertyName = ((MemberExpression)((BinaryExpression)customerfilter.Body).Left).Member.Name;
var propertyValue = ((ConstantExpression)((BinaryExpression)customerfilter.Body).Right).Value;
If you want to support more complicated expressions, ExpressionVisitor
should be use to parse the expression
tree.