C# 包含多个条件的LINQ条件Where子句

C# 包含多个条件的LINQ条件Where子句,c#,linq,if-statement,C#,Linq,If Statement,我正试图构建一个LINQ语句,它解释where子句中的两个不同条件,但我还没有找到一个解决方案 我有一个试图查询的流程步骤列表: stepsQuery = _context.ProcessSteps .Where(a.StepType == Constants.ProcessStepTypes.Standard) if (includeA) stepsQuery = stepsQuery.Where(u => u.StepType == Constants.Process

我正试图构建一个LINQ语句,它解释where子句中的两个不同条件,但我还没有找到一个解决方案

我有一个试图查询的流程步骤列表:

stepsQuery = _context.ProcessSteps
    .Where(a.StepType == Constants.ProcessStepTypes.Standard)

if (includeA)
    stepsQuery = stepsQuery.Where(u => u.StepType == Constants.ProcessStepTypes.A);

if (includeB)
    stepsQuery = stepsQuery.Where(u => u.StepType == Constants.ProcessStepTypes.B);

我有两个传入的变量,includeA和includeB。我需要所有的标准步骤,如果includeA为真,还需要A步骤,如果includeB为真,还需要B步骤。如果可能的话,我想把这一切都写进一句话里。我一直在玩“contains”,但我不能完全让它工作。

你可以简单地将
stepsQuery
写成

_context.ProcessSteps.Where(a => a.StepType == Constants.ProcessStepTypes.Standard ||
    includeA && a.StepType == Constants.ProcessStepTypes.A ||
    includeB && a.StepType == Constants.ProcessStepTypes.B)

您可以通过
包含
来实现这一点:

stepsQuery = .AsQueryable();

var stepTypes = new List<string>();
stepTypes.Add(Constants.ProcessStepTypes.Standard);
if (includeA)
    stepTypes.Add(Constants.ProcessStepTypes.A);
if (includeB)
    stepTypes.Add(Constants.ProcessStepTypes.B);

var stepsQuery = _context.ProcessSteps.Where(u => stepTypes.Contains(u.StepType));
stepsQuery=.AsQueryable();
var stepTypes=新列表();
添加(常量.ProcessStepTypes.Standard);
如果(包括a)
添加(Constants.ProcessStepTypes.A);
如果(包括b)
Add(Constants.ProcessStepTypes.B);
var stepsQuery=_context.ProcessSteps.Where(u=>stepTypes.Contains(u.StepType));

u.StepType的类型是什么?此代码令人困惑。如果
includeA
includeB
都为真,您希望发生什么?因为看起来如果它们都是真的,那么就不会包含任何项目。如果两者都是假的,你希望发生什么?这包括一切。用一个例子更清楚地说明你希望代码做什么。@HereticMonkey不,他现在替换的代码不包括。如果他使用的是
stepsQuery=stepsQuery.Concat(stepsQuery.Where…
),那么它将按原样工作。@EricLippert OP已经说明了他试图完成的内容“我需要所有标准步骤,如果includeA为真,还需要A步骤,如果includeB为真,还需要B步骤。”我们通常会邀请人们展示他们的尝试,因此,考虑到他们首先提出的问题,允许非工作代码也似乎是公平的;他们确实说他们不能让自己的代码工作,也没有声称自己的代码工作。我还发现代码后面的文本解释非常清晰,几乎不知道如何解释MichaelPuckettII:这就是它的作用。你总是会得到
a.StepType==Constants.ProcessStepTypes.Standard
但是如果,比如说,
includeA
,那么你也会得到
a.StepType==Constants.ProcessStepTypes.a
@MichaelPuckettII:谓词会对每个元素。为了清楚起见,因为我对其他人可能也感到困惑;我建议用这个答案格式化整个查询。@MichaelPuckettII:有道理;我知道这很容易被误读。让我相应地更新答案。@TrevorGoodchild:太好了,不客气。如果谓词变得复杂,这种方法当然会变得笨拙y、 在这些情况下,您可能会在中找到一些用途,这也适用于您的情况。