Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract the property name and value being passed into an Expression<Func<T,bool>>?

Tags:

c#

lambda

Let's assume 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 into the Get extension method?

like image 761
DDiVita Avatar asked Sep 15 '11 15:09

DDiVita


1 Answers

I think this is what you're 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...

like image 196
Ray Avatar answered Oct 12 '22 22:10

Ray