PageRenderTime 16ms CodeModel.GetById 8ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/Services/PredicateBuilder.cs

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