PredicateBuilder.cs 1018 B

123456789101112131415161718192021222324252627
  1. using System;
  2. using System.Linq.Expressions;
  3. namespace CommonTool
  4. {
  5. public static class PredicateBuilder
  6. {
  7. public static Expression<Func<T, bool>> True<T>() { return f => true; }
  8. public static Expression<Func<T, bool>> False<T>() { return f => false; }
  9. public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
  10. Expression<Func<T, bool>> expr2)
  11. {
  12. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters);
  13. return Expression.Lambda<Func<T, bool>>
  14. (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
  15. }
  16. public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
  17. Expression<Func<T, bool>> expr2)
  18. {
  19. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters);
  20. return Expression.Lambda<Func<T, bool>>
  21. (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
  22. }
  23. }
  24. }