Reputation: 1207
Supposing I have the following LambdaExpression:
var itemParam = Expression.Parameter(typeof(Thing), "thing");
var someValue = "ABCXYZ123"; // value to compare
LambdaExpression lex = Expression.Lambda(
Expression.Equal(
Expression.Property(itemParam, "Id"), // I want ID to be a Body expression parameter
Expression.Constant(someValue)
), itemParm);
And I want the property name (2nd parameter) in the Expression.Property(...) factory to be a parameter, how do I go about doing this?
I was hoping to see a constructor that looks like this, but it doesn't exist:
Expresssion.Property(Expression instance, Expression propName)
Is there some trick I can pull that can convert a parameterized ConstantExpression into the needed string or MemberInfo? Maybe I'm going about this the wrong way.
My hunch is that because these expression trees, when compiled, become lightweight IL, that member access information is required, thus, the names of members and properties must be provided when constructing expression trees.
Thanks for any tips!!
EDIT: Wanted to add that this will be used as an argument to the Enumerable.Where(...) extension method for determining a match on a relationship between two classes / entities.
Upvotes: 4
Views: 447
Reputation: 726699
Expression trees represent IL structures that are roughly of the same kind that you see in your C#/VB.NET programs. You cannot parameterize that property expression for the same reason that you cannot "parameterize" the following code:
var x = new MyClass {Id = 1, Name = "hello"};
var propName = "Id";
var xId = x.propName; // <-- This will not compile
If you need to implement this functionality, and your expression trees are not passed to IQueryable<T>
, you can write a helper function taking an object and a string, and returning value of that object's property identified by the string; then you can use Expression.Call
to invoke that helper function into the expression tree that you are building.
Upvotes: 2