C# 如何将两个表达式组合成一个新表达式?
我有两个表达式:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只是尝试将表达式主体与
AndAlso
表达式组合,您将遇到的问题是x
参数表达式实际上是两个不同的参数(即使它们具有同名)。为此,您需要使用表达式树访问器来替换要与单个通用ParameterExpression
组合的两个表达式中的x
。您可能需要查看 Joe Albahari 的 PredicateBuilder 库,它会为您完成繁重的工作。结果应该类似于:
The problem you'll run into if you just try combining the expression bodies with an
AndAlso
expression is that thex
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 thex
in the two expressions you want to combine with a single, commonParameterExpression
.You may want to look at Joe Albahari's PredicateBuilder library, which does the heavy lifting for you. The result should look something like: