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

╄→尐↘猪︶ㄣ 提交于 2019-12-22 14:51:54

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/8840981/c-sharp-how-to-combine-two-expressions-into-a-new-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!