PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Services/PredicateBuilder.cs

#
C# | 24 lines | 21 code | 3 blank | 0 comment | 0 complexity | 5c9f0c8ae2cb8b754739399fcb0c0d4a MD5 | raw file
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. namespace Contrib.Voting.Services {
  5. public static class PredicateBuilder {
  6. public static Expression<Func<T, bool>> True<T>() { return f => true; }
  7. public static Expression<Func<T, bool>> False<T>() { return f => false; }
  8. public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
  9. Expression<Func<T, bool>> expr2) {
  10. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
  11. return Expression.Lambda<Func<T, bool>>
  12. (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
  13. }
  14. public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
  15. Expression<Func<T, bool>> expr2) {
  16. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
  17. return Expression.Lambda<Func<T, bool>>
  18. (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
  19. }
  20. }
  21. }