Skip to content

Instantly share code, notes, and snippets.

@seesharper
Created November 11, 2015 10:01
Show Gist options
  • Select an option

  • Save seesharper/386c0faddd75b60c8e14 to your computer and use it in GitHub Desktop.

Select an option

Save seesharper/386c0faddd75b60c8e14 to your computer and use it in GitHub Desktop.
Flatten Expression Tree's
/// <summary>
/// Extends the <see cref="Expression"/> class.
/// </summary>
public static class ExpressionExtensions
{
/// <summary>
/// Flattens the <paramref name="expression"/> into an <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="expression">The target <see cref="Expression"/>.</param>
/// <returns>The <see cref="Expression"/> represented as a list of sub expressions.</returns>
public static IEnumerable<Expression> AsEnumerable(this Expression expression)
{
var flattener = new ExpressionTreeFlattener();
return flattener.Flatten(expression);
}
private class ExpressionTreeFlattener : ExpressionVisitor
{
private readonly ICollection<Expression> nodes = new Collection<Expression>();
public IEnumerable<Expression> Flatten(Expression expression)
{
Visit(expression);
return nodes;
}
public override Expression Visit(Expression node)
{
nodes.Add(node);
return base.Visit(node);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment