public static class PredicateExtensions { public static Expression> True () { return f => true; } public static Expression > False () { return f => false; } public static Expression > Or (this Expression > expression1, Expression > expression2) { var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast ()); return Expression.Lambda >(Expression.Or(expression1.Body, invokedExpression), expression1.Parameters); } public static Expression > And (this Expression > expression1, Expression > expression2) { var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast ()); return Expression.Lambda >(Expression.And(expression1.Body, invokedExpression), expression1.Parameters); } public static Expression > Not (this Expression > expression) { var negated = Expression.Not(expression.Body); return Expression.Lambda >(negated, expression.Parameters); } }
用法:
Expression> expression = PredicateExtensions.True ();expression = expression.And(x=> x.Name == "ABC");expression = expression.Or(x=> x.Name == "XYZ");expression = expression.Not();