Guest User

Parameter replacement in a Linq Expression Tree

a guest
Jun 16th, 2011
186
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×