如何使用LINQ链接OR子句? [英] How to chain OR clauses, with LINQ?
问题描述
我有一种情况,我需要使用LINQ构建SQL查询,其中包括可变数量的OR子句.我正在编写一个函数,该函数将基于某些输入来构建查询.函数定义看起来类似于...
I've got a scenario where I need to build a SQL query, using LINQ, that includes a variable amount of OR clauses. I'm writing a function that will build the query based on some input. The function definition looks something similar to ...
function BuildQuery(ICollection<ColumnsThatNeedToBeTrue> columns)
{
...
}
因此,我得到了一组需要检查是否为true的列,并且该检查需要使用OR
子句.
So, I'm given a collection of columns that I need to check for true, and the check needs to use OR
clauses.
如果columns
数组包含A
和B
,则需要查询以检查列A
是true还是列B
是true.
If the columns
array contains A
and B
, I'd need the query to check if column A
is true OR column B
is true.
如果columns
数组包含A
,B
和C
,则需要查询并检查A
或B
或C
是否为真.
If the columns
array contains A
, B
and C
, I'd need to query and check if A
OR B
OR C
are true.
我不知道如何在单个Where
中完成所有这些操作,因为我不知道一种逐步处理其他||
子句的方法.我不确定如何根据输入数组在下面添加其他OR检查.
I don't know how to do this all within a single Where
, because I don't know of a way to progressively tack on additional ||
clauses. I'm not sure how I'd include additional OR checks in the below, based on the input array.
var query = entities.Where(m => m.A == true || m.B == true ...)
我无法链接Where
函数,每个函数都进行各自的列检查,因为它使用AND
子句构建了该查询,并且我需要OR
.
I cannot chain Where
functions, each for their own column check, because it builds that query using AND
clauses and I need OR
.
有没有一种使用LINQ建立这样的查询的方法?
Is there a way to build out a query like this, using LINQ?
推荐答案
您可以使用 PredicateBuilder 链接or
条件.
var predicate = PredicateBuilder.False<SomeEntity>();
predicate = predicate.Or (p => p.A == true);
if(something)
predicate = predicate.Or (p => p.B == true);
var query = entities.AsExpandable().Where (predicate); //AsExpandable() for EF
这篇关于如何使用LINQ链接OR子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!