C#如何将两个表达式组合成一个新表达式?

Rya*_*eir 2 c# linq lambda expression

我有两个表达式:

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

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

我想创建一个同时应用两个表达式的新表达式(我的代码在不同的组合中使用相同的表达式):

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

然后做:

public static class IntegerExtensions
{
    public static bool IsValid(this int self) 
    {
        return IsValidExpression().Compile()(self);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中:

if (32.IsValid()) {
   //do something
}
Run Code Online (Sandbox Code Playgroud)

我有很多这样的表达式,我想要定义一次而不是在整个地方复制代码.

谢谢.

Str*_*ior 6

如果您只是尝试将表达式主体与AndAlso表达式组合,那么您将遇到的问题是x参数表达式实际上是两个不同的参数(即使它们具有相同的名称).为此,您需要使用表达式树访问者来替换x要与单个公共组合的两个表达式ParameterExpression.

你可能想看看Joe Albahari的PredicateBuilder库,它可以为你提供繁重的工作.结果应该类似于:

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