/
PredicateBuilder.cs
52 lines (46 loc) · 1.98 KB
/
PredicateBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Linq;
using System.Linq.Expressions;
using Simple.Expressions;
namespace Simple
{
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>()
{
return True<T>(Expression.Parameter(typeof(T), "f"));
}
public static Expression<Func<T, bool>> True<T>(ParameterExpression param)
{
return Expression.Lambda<Func<T, bool>>(Expression.Constant(true), param);
}
public static Expression<Func<T, bool>> False<T>()
{
return False<T>(Expression.Parameter(typeof(T), "f"));
}
public static Expression<Func<T, bool>> False<T>(ParameterExpression param)
{
return Expression.Lambda<Func<T, bool>>(Expression.Constant(false), param);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
if (expr1 == null) expr1 = False<T>();
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters).ExpandInvocations();
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
if (expr1 == null) expr1 = True<T>();
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters).ExpandInvocations();
}
public static Expression<Func<T, bool>> ExpandInvocations<T>(this Expression<Func<T, bool>> expr)
{
return InvocationExpander.Expand(expr);
}
}
}