Can I parameterize the property name of PropertyExpression using LINQ expressions?

Suppose I have the following LambdaExpression expression:

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 element to be the parameter, how can I do 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 any trick I can do that can convert a parameterized ConstantExpression to the desired string or MemberInfo? Maybe I'm wrong.

My guess is that since these expression trees, when they are compiled, become lightweight ILs, this member access information is required, so element and property names must be provided when building expression trees.

Thanks for any tips!

EDIT: I wanted to add that this will be used as an argument for the Enumerable.Where (...) extension method to determine the correspondence for the relationship between two classes / entities.

+4
source share
1 answer

Expression trees represent IL structures that are about the same type that you see in your C # / VB.NET programs. You cannot parameterize this 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 that takes an object and a string and returns the value of this property of the object identified by the string; then you can use Expression.Call to call this helper function in the expression tree you are building.

+2
source

Source: https://habr.com/ru/post/1390485/


All Articles