Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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));
		}
	}

Bookmark and Share
Posted: Dec 14 2010, 12:11 PM by Ricardo Peres | with 3 comment(s)
Filed under: ,

Comments

SamZ said:

Could you provide sample of usage?

# December 14, 2010 7:48 AM

Ricardo Peres said:

SamZ,

Sure:

Expression<Func<int, bool>> isEven = i => (i % 2) == 0;

Expression<Func<int, bool>> isMultipleOfFive => i => (i % 5) == 0;

Expression<Func<int, bool>> evenOrMultipleOfFive = isEven.Or(isMultipleOfFive);

Expression<Func<int, bool>> isOdd = isEven.Not();

And so on.

# December 14, 2010 8:55 AM

weblogs.asp.net said:

Basic logical operations with linq expressions.. Bang-up :)

# May 28, 2011 9:10 PM