Created
November 11, 2015 10:01
-
-
Save seesharper/386c0faddd75b60c8e14 to your computer and use it in GitHub Desktop.
Flatten Expression Tree's
This file contains hidden or 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
| /// <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