[NoBrainer] Cascading Lambda Expression in C#

While Converting ODataQueryOptions into LINQ Expressions I needed to cascade different Lambda Expressions via AND and OR. In this post I describe a way on how to easily combine them via a boxing class with operator overriding.

The Problem

Cascading lambda expressions should be as easy as using a + or && operator:

Expression<Func<SomeObject, bool>> expression1 = e => e.Id != 0;

Expression<Func<SomeObject, bool>> expression2 = e => !string.IsNullOrWhiteSpace(e.Name);
var result1 = boxed + expression2;

A boxing class

However, as by default Expressions or LambdaExpressions do not support these operators we need to define our own boxing class:

using BoxedType=System.Linq.Expressions.LambdaExpression;

public sealed class BoxedLambdaExpression : Boxed<BoxedType>
{
  public static BoxedType operator +(BoxedLambdaExpression expression1, BoxedType expression2)
  {
    return Combine(expression1, expression2, false);
  }

  public static BoxedType operator &(BoxedLambdaExpression expression1, BoxedType expression2)
  {
    return Combine(expression1, expression2, false);
  }

  public static BoxedType operator |(BoxedLambdaExpression expression1, BoxedType expression2)
  {
    return Combine(expression1, expression2, true);
  }
}

As we cannot override logical and or logical or I choose to override bitwise and and bitwise or (in addition to +).

Note: the boxing class derives from our generic Boxed type that streamlines the conversion process and also aupports IConvertible which in this case does not make too much sense.

Implicit cast operators

In order to faciliate using these overridden operators without explicitly using our boxing class, we define static conversion/cast operators:

public static implicit operator BoxedType(BoxedLambdaExpression lambdaExpression)
{
  return lambdaExpression.Value;
}

public static implicit operator BoxedLambdaExpression(BoxedType boxedExpression)
{
  return new BoxedLambdaExpression
  {
    Value = boxedExpression
  };
}

The only thing the ExpressionVisitor does it replacing the MemberExpression with a new expression to combine both expressions.

Cascading Expressions

The actual step of combining the lambda expressions is easy as creating a new expression by using Expression.AndAlso or Expression.OrElse:

private const int PARAMETER_COUNT = 1;
private const int PARAMETER_INDEX = 0;
private const string PARAMETER_NAME = "$it";

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static BoxedType Combine(BoxedLambdaExpression expression1, BoxedType expression2, bool isOrElse)
{
  var combinedExpression = isOrElse
    ? Expression.OrElse(expression1.Value.Body, expression2.Body)
    : Expression.AndAlso(expression1.Value.Body, expression2.Body);
  var visitor = new MemberExpressionVisitor(Expression.Parameter(expression1.Value.Parameters[PARAMETER_INDEX].Type, PARAMETER_NAME));
  var replacedExpression = visitor.Visit(combinedExpression);

  var lambdaType = typeof(Func<,>).MakeGenericType(visitor.Parameter.Type, expression1.Value.ReturnType);
  return Expression.Lambda(lambdaType, replacedExpression, visitor.Parameter);
}

This is all it takes to combine lambda expressions in a simple manner like this:

Expression<Func<SomeObject, bool>> expression1 = e => e.Id != 0;
Expression<Func<SomeObject, bool>> expression2 = e => !string.IsNullOrWhiteSpace(e.Name);

var result = (BoxedLambdaExpression) expression1 + expression2;

// result contains the following lambda expression
// @"$it => (($it.Id != 0) AndAlso Not(IsNullOrWhiteSpace($it.Name)))"

The complete code is available at the following gist (or inlined below): https://gist.github.com/dfch/951d355ad929fba966aec7dccd67d199

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: