简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM