猿问

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

我正在尝试构建一个 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 步骤。如果可能的话,我试图将所有这些都放在一个声明中。我一直在玩“包含”,但我无法让它发挥作用。


慕莱坞森
浏览 403回答 2
2回答

一只名叫tom的猫

你可以简单地写stepsQuery为_context.ProcessSteps.Where(a => a.StepType == Constants.ProcessStepTypes.Standard ||     includeA && a.StepType == Constants.ProcessStepTypes.A ||     includeB && a.StepType == Constants.ProcessStepTypes.B)

慕桂英4014372

您可以通过以下方式实现Contains:stepsQuery = .AsQueryable();var stepTypes = new List<string>();stepTypes.Add(Constants.ProcessStepTypes.Standard);if (includeA)&nbsp; &nbsp; stepTypes.Add(Constants.ProcessStepTypes.A);if (includeB)&nbsp; &nbsp; stepTypes.Add(Constants.ProcessStepTypes.B);var stepsQuery = _context.ProcessSteps.Where(u => stepTypes.Contains(u.StepType));
随时随地看视频慕课网APP
我要回答