Ryan
Ryan

Reputation: 6517

C# how to combine two expressions into a new one?

I have two expressions:

public static Expression<Func<int, bool>> IsDivisibleByFive() {
   return (x) => x % 5 == 0;
}

and

public static Expression<Func<int, bool>> StartsWithOne() {
   return (x) => x.ToString().StartsWith("1");
}

And I want to create a new expression that applies both at once (the same expressions are used all over my code in different combinations):

public static Expression<Func<int, bool>> IsValidExpression() {
   return (x) => IsDivisibleByFive(x) && StartsWithOne(x);
}

Then do:

public static class IntegerExtensions
{
    public static bool IsValid(this int self) 
    {
        return IsValidExpression().Compile()(self);
    }
}

And in my code:

if (32.IsValid()) {
   //do something
}

I have many such expressions that I want to define once instead of duplicating code all over the place.

Thanks.

Upvotes: 2

Views: 3430

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

The problem you'll run into if you just try combining the expression bodies with an AndAlso expression is that the x parameter expressions are actually two different parameters (even though they have the same name). In order to do this, you would need to use an expression tree visitor to replace the x in the two expressions you want to combine with a single, common ParameterExpression.

You may want to look at Joe Albahari's PredicateBuilder library, which does the heavy lifting for you. The result should look something like:

public static Expression<Func<int, bool>> IsValidExpression() {
   return IsDivisibleByFive().And(StartsWithOne());
}

Upvotes: 6

Related Questions