我有两个类型的表达式,Expression<Func<T, bool>>我想采取OR,AND或NOT这些并得到一个相同类型的新表达式
Expression<Func<T, bool>> expr1;
Expression<Func<T, bool>> expr2;
...
//how to do this (the code below will obviously not work)
Expression<Func<T, bool>> andExpression = expr AND expr2
Run Code Online (Sandbox Code Playgroud) 在我以后的EF中,我试图传入一个匿名函数作为我的Linq查询的一部分.该函数将传入INT并返回BOOL(u.RelationTypeId是INT).以下是我的功能的简化版本:
public IEnumerable<UserBandRelation> GetBandRelationsByUser(Func<int, bool> relation)
{
using (var ctx = new OpenGroovesEntities())
{
Expression<Func<UsersBand, bool>> predicate = (u) => relation(u.RelationTypeId);
var relations = ctx.UsersBands.Where(predicate);
// mapping, other stuff, back to business layer
return relations.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到上述错误.看起来我通过从函数构建谓词来使一切正确.有任何想法吗?谢谢.
可能重复:
在c#中组合两个lamba表达式
我有两个以下表达式:
Expression<Func<string, bool>> expr1 = s => s.Length == 5;
Expression<Func<string, bool>> expr2 = s => s == "someString";
Run Code Online (Sandbox Code Playgroud)
现在我需要将它们与OR结合起来.像这样的东西:
Expression.Or(expr1, expr2)
Run Code Online (Sandbox Code Playgroud)
有没有办法使这类似于上面的代码方式:
expr1 || expr2
Run Code Online (Sandbox Code Playgroud)
我理解在这个例子中我可以将它组合在一起:
Expression<Func<string, bool>> expr = s => s.Length == 5 || s == "someString"
Run Code Online (Sandbox Code Playgroud)
但我不能在我的真实代码中这样做,因为我将expr1和expr2作为方法的参数.
那么,以下代码是自我解释的; 我想将两个表达式合并为一个使用And运算符.最后一行导致符文时间错误:
附加信息:从范围''引用的'System.String'类型的变量'y',但未定义
码:
Expression<Func<string, bool>> e1 = y => y.Length < 100;
Expression<Func<string, bool>> e2 = y => y.Length < 200;
var e3 = Expression.And(e1.Body, e2.Body);
var e4 = Expression.Lambda<Func<string, bool>>(e3, e1.Parameters.ToArray());
e4.Compile(); // <--- causes run-time error
Run Code Online (Sandbox Code Playgroud) 我正在尝试基于Specification对象动态构建表达式.
我创建了一个ExpressionHelper类,它有一个私有表达式,如下所示:
private Expression<Func<T, bool>> expression;
public ExpressionHelper()
{
expression = (Expression<Func<T, bool>>)(a => true);
}
Run Code Online (Sandbox Code Playgroud)
然后一些简单的方法如下:
public void And(Expression<Func<T,bool>> exp);
Run Code Online (Sandbox Code Playgroud)
我正在和And方法的身体挣扎.我基本上想要撕掉身体exp,用那些参数替换所有参数expression然后将它附加到expression身体的末端和AndAlso.
我这样做了:
var newBody = Expression.And(expression.Body,exp.Body);
expression = expression.Update(newBody, expression.Parameters);
Run Code Online (Sandbox Code Playgroud)
但最终我的表达看起来像这样:
{ a => e.IsActive && e.IsManaged }
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?或者我怎样才能撕掉那些e并用一个替换它们?