为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕莱坞森 2021-10-24 14:23:16
我正在尝试构建一个 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 步骤。如果可能的话,我试图将所有这些都放在一个声明中。我一直在玩“包含”,但我无法让它发挥作用。
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

你可以简单地写stepsQuery

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


查看完整回答
反对 回复 2021-10-24
?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

您可以通过以下方式实现Contains:


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));


查看完整回答
反对 回复 2021-10-24
  • 2 回答
  • 0 关注
  • 402 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信