gpt4 book ai didi

c# - 只有传入值才做Where条件

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:44 26 4
gpt4 key购买 nike

我有以下 LINQ 语句,它在 dateLabIDwhere 上执行。

我正在传递一个 LABS 列表和一个日期,但它们不是必需的,我可能只传递一个日期,而不传递实验室,在这种情况下,我想获得所有实验室的结果那个特定的实验室。

这是我现在拥有的:

List<dExp> lstDatExp = (from l in ctx.dExp.Include("datLab")
where values.Contains(l.datL.Lab_ID)
&& l.reportingPeriod == reportingPeriod
select l).ToList<dExp>();

但是如果传入的值不存在,这就会中断。我该如何更改它以确保我的两个 where 语句都是可选的?

最佳答案

使用 IQueryable,您可以简单地分步添加条件:

int? reportingPeriod = ...;

IQueryable<dExp> resultsQuery = // don't use `var` here.
ctx.dExp.Include("datLab");

if (values != null)
resultsQuery = resultsQuery.Where(exp => values.Contains(exp.datL.Lab_ID));

if (reportingPeriod.Hasvalue)
resultsQuery = resultsQuery.Where(exp => exp.reportingPeriod == reportingPeriod.Value);

// additional .Where(), .OrderBy(), .Take(), .Skip() and .Select()

// The SQL query is made and executed on the line below
// inspect the string value in the debugger
List<dExp> results = resultsQuery.ToList();

关于c# - 只有传入值才做Where条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com