How to get value from a lambda expression?

.net c# expression-trees lambda

Question

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

Popular Answer

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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why