Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the properties, operators and values from an Expression<Func<T, bool>> predicate?

Is there any way to pull out the properties, the operator and matching value from an Expression<Func<T>,bool>? Given the following example:

var customers = GetCustomers();
var customerQuery = customers.Where(x=> x.CustomerID == 1 
    && x.CustomerName == "Bob"); // The query is for illustration only

I need to be able to get out something like the following:

Property: CustomerID
Operator: Equals
Value:    1

Property: CustomerName
Operator: Equals
Value:    Bob

I've already written something that can pull out the property name of an Expression, but I cannot seem to find out where the value and operator are held, although it's quite clearly visible in the Expression's DebugView property.

like image 493
djdd87 Avatar asked Nov 07 '11 08:11

djdd87


2 Answers

The operator will be on the BinaryExpression's Method that is the Equals node. You should also look at the expressions .NodeType, which reveals much (it should be Equal).

The values will typically be in a ConstantExpression in the .Right of that BinaryExpression, or in the case of a captured variable: the capture-context will be the ConstantExpression, so the value will be a MemberExpression over a ConstantExpression (you will need to investigate whether the member is a FieldInfo vs PropertyInfo, and fetch the value via .GetValue(...) on that).

like image 167
Marc Gravell Avatar answered Sep 21 '22 22:09

Marc Gravell


In addition to Marc Gravells answer (+1 there) I'll just add that it's worth taking a look at the ExpressionVisitor class (out of the box in .Net 4; MSDN has an example that you can copy/paste for 3.5). It makes writing code to extract certain types of expression very very easy.

In your case you would be looking to override it's VisitBinary method.

I typically use the class to push the expression(s) I'm interested in into a read-only list, for example, which I then make available publicly on my implementation of the class. You're not using it to rewrite the expression.

like image 37
Andras Zoltan Avatar answered Sep 22 '22 22:09

Andras Zoltan