Expression tree for a member access of depth > 1

c# expression expression-trees lambda linq

Question

public class Job
{
    public string Name { get; set; }
    public int Salary { get; set; }
}
public class Employee
{
    public string Name { get; set; }
    public Job Job { get; set; }
}

If I want to create an expression tree of a member access to Employee.Name this is what I do:

        var param = Expression.Parameter(type, "x");
        var memberAccess = Expression.PropertyOrField(param, memberName);
        return Expression.Lambda<Func<TModel, TMember>>(memberAccess, param);

What is the equivalent to this for a member access to Employee.Job.Salary ?

Accepted Answer

You need:

var jobProperty = Expression.PropertyOrField(param, "Job");
var salaryProperty = Expression.PropertyOrField(jobProperty, "Salary");

Basically you're taking the Salary property from the result of evaluating x.Job.

If you need to do this in a programmatic way, you'll need something like:

Expression expression = Expression.Parameter(type, "x");
foreach (var property in properties.Split('.'))
{
    expression = Expression.PropertyOrField(expression, property);
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow