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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With