问题描述
我想知道如何通过输入多个参数来制作表达式树
I would like to know how to be able to make an Expression tree by inputting more than one parameter
示例:
dataContext.Users.Where(u => u.username == "Username" && u.password == "Password")
目前,我执行的代码如下,但希望对条件是OR还是AND进行更一般的说明.
At the moment the code that I did was the following but would like to make more general in regards whether the condition is OR or AND
public Func<TLinqEntity, bool> ANDOnlyParams(string[] paramNames, object[] values)
{
List<ParameterExpression> paramList = new List<ParameterExpression>();
foreach (string param in paramNames)
{
paramList.Add(Expression.Parameter(typeof(TLinqEntity), param));
}
List<LambdaExpression> lexList = new List<LambdaExpression>();
for (int i = 0; i < paramNames.Length; i++)
{
if (i == 0)
{
Expression bodyInner = Expression.Equal(
Expression.Property(
paramList[i], paramNames[i]),
Expression.Constant(values[i]));
lexList.Add(Expression.Lambda(bodyInner, paramList[i]));
}
else
{
Expression bodyOuter = Expression.And(
Expression.Equal(
Expression.Property(
paramList[i], paramNames[i]),
Expression.Constant(values[i])),
Expression.Invoke(lexList[i - 1], paramList[i]));
lexList.Add(Expression.Lambda(bodyOuter, paramList[i]));
}
}
return ((Expression<Func<TLinqEntity, bool>>)lexList[lexList.Count - 1]).Compile();
}
谢谢
推荐答案
Expression.And
在这里使用是错误的,是按位的.您要AndAlso
.
Expression.And
is the wrong thing to use here, it's the bitwise and. You want AndAlso
.
除了您之外,您似乎已经了解如何构建表达式树的机制.因此,您真正要问的是如何让构建方法的调用者指定一种更复杂,更灵活的组合不同条件的方式.
It seems like you aside from that you already know the mechanics of how to build the expression tree. So what you're really asking is how can you let the caller of your building-method specify a more complicated, flexible way of combining different conditions.
最终,要真正实现灵活性,您需要一种迷你查询语言.解析语言以构建表达式树.
Ultimately for true flexibility you need a mini query language. Parse the language to build the expression tree.
短期内,您可能会遇到一些更简单的事情:原始表达式列表和bool标志,用于说明是否应将它们与&&组合使用.或||.
In the short term, you might get by with something much simpler: a list of primitive expressions and a bool flag to say whether they should be combined with && or ||.
更新-我注意到您实际上是将结果表达式编译成一个真正的委托.这使我想知道为什么您首先要这样做很困难.为什么不像最初的示例那样仅将表达式写为lambda? (如果您使用的是Linq to SQL或EF,则无论如何都不应该编译该表达式.)
Update - I notice you're actually compiling the resulting expression into a real delegate. This makes me wonder why you're doing this the hard way in the first place. Why not just write the expression as a lambda, as in your initial example? (If you're using Linq to SQL or EF, you shouldn't be compiling the expression anyway.)
更新2 -您可能需要的是动态Linq .
这篇关于Lambda表达式在运行时C#的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!