Created
December 14, 2011 21:04
-
-
Save devoyster/1478517 to your computer and use it in GitHub Desktop.
LambdaExpression visitor which reduces variables by transforming them to constants (if possible)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class VariablesReductionVisitor : ExpressionVisitor | |
{ | |
private List<Expression> _children; | |
public override Expression Visit(Expression node) | |
{ | |
// Preserve parent's child expressions collection | |
var siblings = _children; | |
_children = new List<Expression>(); | |
node = base.Visit(node); | |
// If all the child expressions are constants then current one should be constant as well | |
if (_children.Any() && _children.All(e => e == null || e is ConstantExpression)) | |
{ | |
// Evaluate expression locally | |
node = Expression.Constant(Expression.Lambda(node).Compile().DynamicInvoke(), node.Type); | |
} | |
// Add to parent's child expressions collection | |
if (siblings != null) | |
{ | |
siblings.Add(node); | |
} | |
_children = siblings; | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment