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

c# expression-trees lambda

Question

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.

Accepted Answer

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);


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