fork download
  1. using System;
  2. using System.Linq.Expressions;
  3.  
  4. public class Test
  5. {
  6.  
  7.  
  8. public static Expression<Func<T, bool>> Or<T>(
  9. Expression<Func<T, bool>> source, Expression<Func<T, bool>> expression
  10. ) {
  11. if (source == null)
  12. return expression;
  13. var p = Expression.Parameter(typeof(T));
  14. return (Expression<Func<T,bool>>)Expression.Lambda(
  15. Expression.Or(
  16. Expression.Invoke(source, p)
  17. , Expression.Invoke(expression, p)
  18. )
  19. , p
  20. );
  21. }
  22.  
  23. public static void Main()
  24. {
  25. Expression<Func<int,bool>> a = x=>x > 5;
  26. Expression<Func<int,bool>> b = x=>x < -5;
  27. var or = Or(a, b);
  28. var f = (Func<int,bool>)or.Compile();
  29. for (int i = -10 ; i <= 10 ; i++) {
  30. Console.WriteLine("{0} - {1}", i, f(i));
  31. }
  32. }
  33. }
Success #stdin #stdout 0.05s 134784KB
stdin
Standard input is empty
stdout
-10 - True
-9 - True
-8 - True
-7 - True
-6 - True
-5 - False
-4 - False
-3 - False
-2 - False
-1 - False
0 - False
1 - False
2 - False
3 - False
4 - False
5 - False
6 - True
7 - True
8 - True
9 - True
10 - True