我正在尝试构建一个 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 回答
![?](http://img1.sycdn.imooc.com/54584f8f00019fc002200220-100-100.jpg)
一只名叫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)
![?](http://img1.sycdn.imooc.com/545868190001d52602200220-100-100.jpg)
慕桂英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));
- 2 回答
- 0 关注
- 402 浏览
添加回答
举报
0/150
提交
取消