How Create programmaticaly Expression.Lambda<Func<TEntity, TProperty>> with variable Type?

I want to create below code

var lambda = Expression.Lambda<Func<TEntity, TProperty>>(expName, entity);

but TProperty type is variable and change in loop and i can get type of this :

var nameType = typeof(TEntity).GetProperty(name);

I want to have like this

var lambda = Expression.Lambda<Func<TEntity, nameType>>(expName, entity);

Can I create this ?

Jon Skeet
people
quotationmark

You can use Expression.Lamdba(Type, Expression, params ParameterExpression[]) - you'd use typeof(Func<,>).MakeGenericType(typeof(TEntity), nameType) to create the relevant type.

That will just give you a LambdaExpression though. It's not clear what you're trying to do with the result, but you won't have a strongly-typed expression you can invoke. (It will build the right delegate type when you compile it though.)

people

See more on this question at Stackoverflow