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

Is there a way to pull properties, operator and match value from Expression<Func<T>,bool> ? In 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 remove something like the following:

 Property: CustomerID Operator: Equals Value: 1 Property: CustomerName Operator: Equals Value: Bob 

I already wrote something that can pull out the name of the property of an expression, but I cannot figure out where the value and the operator are stored, although it is quite clearly visible in the Expression DebugView property.

+6
source share
2 answers

The statement will be in the BinaryExpression Method , which is the Equals node. You should also look at .NodeType expressions that show a lot (this should be Equal ).

The values ​​are usually found in ConstantExpression in .Right this BinaryExpression , or in the case of a captured variable: context-context will be ConstantExpression , so the value will be MemberExpression over a ConstantExpression (you will need to find out if the FieldInfo vs PropertyInfo element is FieldInfo and select this value via .GetValue(...) ).

+8
source

In addition to Mark Gravel's 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). This makes the write code to extract some types of expressions very easy.

In your case, you would like to override the VisitBinary method.

I usually use a class to push the expression (s) that interests me into a read-only list, which I then provide publicly for my implementation of this class. You do not use it to overwrite an expression.

+3
source

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


All Articles