How to extract the name and value of a property passed to the expression <Func <T, bool >>?

Suppose I have a method like this:

public static List<T> Get<T>(this SomeObject<T>, Expressions<Func<T,bool>> e){ //get the property name and value they want to check is true / false ... } TheObject().Get(x => x.PropertyName == "SomeValue"); 

How do I get "PropertyName" and "SomeValue" when I pass it to the Get extension method?

+7
source share
3 answers

I think this is what you are after

 BinaryExpression expression = ((BinaryExpression)e.Body); string name = ((MemberExpression)expression.Left).Member.Name; Expression value = expression.Right; Console.WriteLine(name); Console.WriteLine(value); 

Output:

 PropertyName SomeValue 

Error checking is left as an exercise for the reader ...

+9
source
  var expressionBody= e.Body.ToString(); 

will return a string as shown below:

 //"(x.PropertyName == \"SomeValue\")" 

there is a more accurate way to do this (for example, compile it), but the compilation performance of the expression is really bad for what you ask

0
source

The System.Web.Mvc can help you flip this. Take a look at ModelMetadata.FromLambdaExpression<TParameter, TValue>

0
source

All Articles