4

I need to Create the following Lambda Expression :

{d=>d.Name.NameEn}

I wrote the following code:

ParameterExpression parameter = Expression.Parameter(typeof(T), "d");
MemberExpression memberExpression = Expression.Property(parameter, typeof(T).GetProperty("Name"));
LambdaExpression lambda = Expression.Lambda(memberExpression, parameter);

Output :

{d => d.Name}

But I need this :

{d=>d.Name.NameEn}

How to make this ?

update:

my class :

 public class T
    {
        public U Name { get; set; }
    }
    public class U
    {
        public string NameEn { get; set; }
    }

2 Answers 2

1

In that case you need to wrap the expression in another MemberExpression, e.g.:

var outerMemberExpression = Expression.Property(memberExpression, typeof(U).GetProperty("NameEn"));

and use that for your lambda expression. You do have two member access expressions there, after all: One to access Name, and one to access NameEn.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try:

ParameterExpression parameter = Expression.Parameter(typeof(T), "d");
MemberExpression memberExpression = 
    Expression.Property(parameter, typeof(T).GetProperty("Name"));
MemberExpression memberExpressionInner = 
    Expression.Property(memberExpression,
                        typeof(T).GetProperty("Name").PropertyType.GetProperty("NameEn"));
LambdaExpression lambda = Expression.Lambda(memberExpressionInner, parameter);

Or, if U is known at runtime (I was assumming T would be a generic parameter before your update), the third line could be:

MemberExpression memberExpressionInner = 
    Expression.Property(memberExpression, typeof(U).GetProperty("NameEn"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.