Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a node/property to an Expression Tree

This is the first time I've really dealt with Expression Trees, and I am a bit lost. I apologise if this question just doesn't make any sense at all. Consider the following classes:

public class Foo<T> {
    public T Value { get; set; }
    public bool Update { get; set;}
}

public class Bar {
    public Foo<bool> SomeBool { get; set; }
    public Foo<string> SomeString { get; set; }
}

So right now I have a helper method that looks like this:

public void Helper<T>(Expression<Func<Bar, Foo<T>>> baseExpression, Expression<Func<Bar, T>> valExpression, Expression<Func<Bar, bool>> updateExpression) 
{
    // Do some stuff with those expressions.
}

And then it gets invoked like this:

Helper(b=>b.SomeBool,b=>b.SomeBool.Value,b=>b.SomeBool.Update);

But I dislike building three almost exact same expressions, and having to explicitly pass them into the Helper. What I would prefer is to something like this:

Helper(b=>b.SomeBool);

And then:

public void Helper<T>(Expression<Func<Bar, Foo<T>>> baseExpression) 
{
    // Do some stuff
    var valExpression = ???; // append `.Value` to baseExpression
    var updateExpression = ???; // append `.Update` to baseExpression
}

But I'm not really sure how to do that... Its boggling my mind, any shove in the right direction would be wildly appriciated.

like image 372
J. Holmes Avatar asked Jan 09 '12 20:01

J. Holmes


1 Answers

Sure; if you have baseExpression, then something like:

var valExpression = Expression.Lambda<Func<Bar, T>>(
    Expression.PropertyOrField(baseExpression.Body, "Value"),
    baseExpression.Parameters);
var updateExpression = Expression.Lambda<Func<Bar, bool>>(
    Expression.PropertyOrField(baseExpression.Body, "Update"),
    baseExpression.Parameters);
like image 55
Marc Gravell Avatar answered Oct 31 '22 11:10

Marc Gravell