Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Parameter replacement in a Linq Expression Tree

By: a guest on Jun 16th, 2011  |  syntax: C#  |  size: 0.83 KB  |  views: 117  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. void Main()
  2. {
  3.     Expression<Func<string, int>> expr = s => s.Length;
  4.     expr.Dump();
  5.    
  6.     var visitor = new ParameterReplacementVisitor(
  7.         expr.Parameters[0],
  8.         Expression.Parameter(typeof(string), "x"));
  9.    
  10.     var newExpr = visitor.Visit(expr);
  11.     newExpr.Dump();
  12. }
  13.  
  14. public class ParameterReplacementVisitor : ExpressionVisitor
  15. {
  16.     private readonly ParameterExpression _oldParam;
  17.     private readonly ParameterExpression _newParam;
  18.     public ParameterReplacementVisitor(ParameterExpression oldParam, ParameterExpression newParam)
  19.     {
  20.         _oldParam = oldParam;
  21.         _newParam = newParam;
  22.     }
  23.    
  24.     protected override Expression VisitParameter(ParameterExpression parameter)
  25.     {
  26.         if (parameter == _oldParam)
  27.             return _newParam;
  28.         return parameter;
  29.     }
  30.    
  31. }
clone this paste RAW Paste Data