Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an Expression tree that compares properties in a child object?

How can I create an Expression tree that compares properties in a child object?

For example, I already can create a lambda expression tree that compares direct properties of an object. Like this:

var propertyName = "JobNumber";
var propertyValue = "1005";
Type entityType = typeof(ParentObject);
OperatorDelegate comparisonMethod = Expression.Equal;

var parameter = Expression.Parameter(entityType, "entity");
var lambda =
    Expression.Lambda<Func<ParentObject, bool>>(
        comparisonMethod(Expression.Property(parameter, propertyName), Expression.Constant(propertyValue)),
        parameter);

Which is (I believe) equivalent to:

entity => entity.JobNumber == "1005";

Where I am getting hung up is trying to figure out how to compare values in the properties of a child object. For example, given:

public class ParentObject
{
    public ChildObject Child { get; set; }

    // more properties of ParentObject
}

public class ChildObject
{
    public string JobNumber { get; set; }
}

How would I build an expression that is the equivalent of:

parentEntity => parentEntity.Child.JobNumber == "1005"

Thanks for any help.

like image 971
quakkels Avatar asked Sep 13 '13 21:09

quakkels


1 Answers

You just need to get the property of the returned property value:

var child = Expression.Property(parameter, "Child");
var jobNumber = Expression.Property(child, propertyName);

var lambda =
    Expression.Lambda<Func<ParentObject, bool>>(
        comparisonMethod(jobNumber, Expression.Constant(propertyValue)),
        parameter);
like image 166
Lee Avatar answered Sep 17 '22 22:09

Lee