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

发布于 2024-12-26 16:42:54 字数 865 浏览 3 评论 0原文

我有两个表达式:

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

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

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

然后执行:

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

在我的代码中:

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

我有很多我想要的这样的表达式定义一次而不是到处重复代码。

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝礼 2025-01-02 16:42:54

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

您可能需要查看 Joe Albahari 的 PredicateBuilder 库,它会为您完成繁重的工作。结果应该类似于:

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

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());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文