Adolfo Perez
Adolfo Perez

Reputation: 2874

How to generate a lambda at runtime passing a property name as string?

I have a list of PolicyTran objects:

List<PolicyTran> AllTransactions;

I need to run a query filtering by a property, e.g:

var insureds = AllTransactions.Select(x => x.Insured).ToList();

That works fine, but I need to pass the x.Insured property at runtime since that property could take different values.

I tried doing:

ParameterExpression x = Expression.Parameter(typeof (PolicyTran),"x");
MemberExpression body = Expression.Property(x, propertyName);
var lambda = Expression.Lambda(body,x).Compile();
var result = AllTransactions.Select(lambda).ToList();

In this case propertyName contains "Insured" or any other PolicyTran property. But I get a compilation error saying that "The type arguments cannot be inferred by the ussage..."

I also tried, but no luck:

ParameterExpression x = Expression.Parameter(typeof (PolicyTran),"x");
var result = AllTransactions.Select(Expression.Lambda<Func<PolicyTran, bool>>(x).Compile()).ToList();

Any ideas??

Upvotes: 2

Views: 619

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40586

Your first attempt is closer to the solution. You just need to call the generic version of Lambda:

var lambda = Expression.Lambda<Func<PolicyTran, object>>(body, x).Compile();

in order to get a Func<PolicyTran, object> delegate.

Otherwise the labda will return a simple System.Delegate from which the LINQ .Select will be unable to infer the types.

Upvotes: 5

Related Questions