Hamed F
Hamed F

Reputation: 840

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 ?

Upvotes: 0

Views: 90

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

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

Upvotes: 2

Related Questions