For example, let's say i have a string property "Document.DocumentType.DocumentCode" with DocumentCode is a nullable decimal type.
How can I build an expression tree for this: x.Document.DocumentType.DocumentCode.开发者_如何学运维GetValueOrDefault() == 4
?
For my real case, I won't know exactly what the linked string property will look like or the levels of properties.
Well, that tree is:
- An equality match, where the left hand side is complicated and the right hand side is a constant expression 4.
- The LHS is a method call
GetValueOrDefault()
on (an expression) - The expression from the previous step is a property access expression
DocumentCode
on (an expression) - The expression from the previous step is a property access expression
DocumentType
on (an expression) - The expression from the previous step is a property access expression
Document
on aParameterExpression
Start from the bottom, and build it up from there. In other words, if you know you're only going to have properties, you'll want to:
- Split the string by "."
- Create a
ParameterExpression
Loop round the set of properties, adding another layer or property access each time, e.g.
currentExpression = Expression.Property(currentExpression, propertyName);
Add a method call at to the expression
- Build an equality comparison using that and whatever constant value you're given
精彩评论