Basic Logical Operations with LINQ Expressions
How to implement basic logical operations (AND, OR, NOT, XOR) with LINQ expressions:
public static class ExpressionExtensions { public static Expression<Func<T, Boolean>> Or<T>(this Expression<Func<T, Boolean>> expr, Expression<Func<T, Boolean>> other) { InvocationExpression invokedExpr = Expression.Invoke(other, expr.Parameters.Cast<Expression>()); return (Expression.Lambda<Func<T, Boolean>>(Expression.OrElse(expr.Body, invokedExpr), expr.Parameters)); } public static Expression<Func<T, Boolean>> Xor<T>(this Expression<Func<T, Boolean>> expr, Expression<Func<T, Boolean>> other) { InvocationExpression invokedExpr = Expression.Invoke(other, expr.Parameters.Cast<Expression>()); return (Expression.Lambda<Func<T, Boolean>>(Expression.ExclusiveOr(expr.Body, invokedExpr), expr.Parameters)); } public static Expression<Func<T, Boolean>> Not<T>(this Expression<Func<T, Boolean>> expr) { return (Expression.Lambda<Func<T, Boolean>>(Expression.Not(expr.Body), expr.Parameters)); } public static Expression<Func<T, Boolean>> And<T>(this Expression<Func<T, Boolean>> expr, Expression<Func<T, Boolean>> other) { InvocationExpression invokedExpr = Expression.Invoke(other, expr.Parameters.Cast<Expression>()); return (Expression.Lambda<Func<T, Boolean>>(Expression.AndAlso(expr.Body, invokedExpr), expr.Parameters)); } }