Created
March 1, 2017 23:15
-
-
Save alex-davies/5baabc4a88f94bceeaaedb70b2f143fa to your computer and use it in GitHub Desktop.
Simple visitor to replace expressions. Works well with https://gist.github.com/codecutout/41cceddd4192d8719b6d1b6ca1263483
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Web.Http.OData.Query; | |
namespace ExpressionUtil | |
{ | |
public class ReplaceVisitor : ExpressionVisitor | |
{ | |
private readonly Expression _search; | |
private readonly Expression _replace; | |
private readonly IEqualityComparer<Expression> _comparer; | |
private ReplaceVisitor(Expression search, Expression replace, IEqualityComparer<Expression> comparer) | |
{ | |
_search = search; | |
_replace = replace; | |
_comparer = comparer; | |
} | |
public override Expression Visit(Expression node) | |
{ | |
if (_comparer.Equals(node, _search)) | |
return _replace; | |
return base.Visit(node); | |
} | |
public static Expression Replace(Expression expression, Expression search, Expression replace, IEqualityComparer<Expression> comparer) | |
{ | |
return new ReplaceVisitor(search, replace, comparer).Visit(expression); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment