Guest User

Combination of 2 lambda expressions

a guest
Jun 16th, 2011
280
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void Main()
  2. {
  3.     Expression<Func<string, bool>> expr1 = s => s.Length > 2;
  4.     expr1.Dump();
  5.     Expression<Func<string, bool>> expr2 = s => s.Length < 10;
  6.     expr2.Dump();
  7.     var expr = CombineLambdas(ExpressionType.OrElse, expr1, expr2);
  8.     expr.Dump();
  9. }
  10.  
  11. public Expression<Func<TArg, TResult>> CombineLambdas<TArg, TResult>(
  12.     ExpressionType binaryType,
  13.     Expression<Func<TArg, TResult>> first,
  14.     Expression<Func<TArg, TResult>> second)
  15. {
  16.     var newParam = first.Parameters[0];
  17.     var oldParam = second.Parameters[0];
  18.     var visitor = new ParameterReplacementVisitor(oldParam, newParam);
  19.     var firstBody = first.Body;
  20.     var secondBody = visitor.Visit(second.Body);
  21.     return Expression.Lambda<Func<TArg, TResult>>(
  22.         Expression.MakeBinary(binaryType, firstBody, secondBody),
  23.         newParam);
  24. }
  25.  
  26. public class ParameterReplacementVisitor : ExpressionVisitor
  27. {
  28.     private readonly ParameterExpression _oldParam;
  29.     private readonly ParameterExpression _newParam;
  30.     public ParameterReplacementVisitor(ParameterExpression oldParam, ParameterExpression newParam)
  31.     {
  32.         _oldParam = oldParam;
  33.         _newParam = newParam;
  34.     }
  35.    
  36.     protected override Expression VisitParameter(ParameterExpression parameter)
  37.     {
  38.         if (parameter == _oldParam)
  39.             return _newParam;
  40.         return parameter;
  41.     }
  42.    
  43. }
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.

×