ExpressionExtensions.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. namespace WWPipeLine.Commons
  6. {
  7. public static class ExpressionExtensions
  8. {
  9. public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
  10. {
  11. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
  12. return Expression.Lambda<Func<T, bool>>(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
  13. }
  14. public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
  15. {
  16. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
  17. return Expression.Lambda<Func<T, bool>>(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
  18. }
  19. public static Expression<Func<T, bool>> WhereAnd<T>(this IEnumerable<Expression<Func<T, bool>>> exprs)
  20. {
  21. Expression<Func<T, bool>> FinalQuery = t => true;
  22. foreach (var expr in exprs)
  23. {
  24. FinalQuery = FinalQuery.And(expr);
  25. }
  26. return FinalQuery;
  27. }
  28. public static Expression<Func<T, bool>> WhereOr<T>(this IEnumerable<Expression<Func<T, bool>>> exprs)
  29. {
  30. Expression<Func<T, bool>> FinalQuery = t => false;
  31. foreach (var expr in exprs)
  32. {
  33. FinalQuery = FinalQuery.Or(expr);
  34. }
  35. return FinalQuery;
  36. }
  37. }
  38. }