This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Combination of 2 lambda expressions

By: a guest on Jun 16th, 2011  |  syntax: C#  |  size: 1.37 KB  |  views: 185  |  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, 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. }
clone this paste RAW Paste Data