Skip to content

Instantly share code, notes, and snippets.

@devoyster
Created December 14, 2011 21:04
Show Gist options
  • Save devoyster/1478517 to your computer and use it in GitHub Desktop.
Save devoyster/1478517 to your computer and use it in GitHub Desktop.
LambdaExpression visitor which reduces variables by transforming them to constants (if possible)
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