如何将LINQ表达式组合为一个? [英] How do I combine LINQ expressions into one?
问题描述
我有一个带有多个字段(公司名称,邮政编码等)的表单,该表单允许用户在数据库中搜索公司.如果用户在多个字段中输入值,那么我需要在所有这些字段中进行搜索.我正在使用LINQ查询数据库.
I've got a form with multiple fields on it (company name, postcode, etc.) which allows a user to search for companies in a database. If the user enters values in more than one field then I need to search on all of those fields. I am using LINQ to query the database.
到目前为止,我已经设法编写了一个函数,该函数将查看它们的输入并将其转换为表达式列表.现在,我想将该List转换为一个表达式,然后可以通过LINQ提供程序执行该表达式.
So far I have managed to write a function which will look at their input and turn it into a List of expressions. I now want to turn that List into a single expression which I can then execute via the LINQ provider.
我最初的尝试如下
private Expression<Func<Company, bool>> Combine(IList<Expression<Func<Company, bool>>> expressions)
{
if (expressions.Count == 0)
{
return null;
}
if (expressions.Count == 1)
{
return expressions[0];
}
Expression<Func<Company, bool>> combined = expressions[0];
expressions.Skip(1).ToList().ForEach(expr => combined = Expression.And(combined, expr));
return combined;
}
但是,此操作失败,并带有二进制操作符And并没有为...定义"的异常消息.有谁知道将这些表达式结合起来需要做什么?
However this fails with an exception message along the lines of "The binary operator And is not defined for...". Does anyone have any ideas what I need to do to combine these expressions?
更正了我忘记分配表达式和将结果一起分配给变量的行.感谢您指出这些人.
Corrected the line where I had forgotten to assign the result of and'ing the expressions together to a variable. Thanks for pointing that out folks.
推荐答案
在表达式树方面,Jason的答案现在比我的完整,所以我删除了这一点.但是,我想离开这个:
Jason's answer is now fuller than mine was in terms of the expression tree stuff, so I've removed that bit. However, I wanted to leave this:
我假设您正在将这些用于Where
子句...为什么不依次用每个表达式调用Where?那应该具有相同的效果:
I assume you're using these for a Where
clause... why not just call Where with each expression in turn? That should have the same effect:
var query = ...;
foreach (var condition in conditions)
{
query = query.Where(condition);
}
这篇关于如何将LINQ表达式组合为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!