仅在传入值时执行 Where 条件
本文关键字:执行 Where 条件 | 更新日期: 2023-09-27 18:34:51
我有以下 LINQ 语句,该语句在date
和LabID
where
上执行。
列表和一个日期,但是它们不是必需的,我可能只能传递一个日期,而不能传递实验室,在这种情况下,我想获得该特定实验室的所有实验室的结果。
这是我现在拥有的:
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();
这里有两种方法可以做到这一点。
但首先,请不要使用单个小写 l 作为标识符。很容易将其与数字 1 混淆。更一般地说,stp 在 yr cde 中使用缩写,它 mks 它 hrdr 到 rd。
第一种技术:
var query = from lab in ctx.dExp.Include("datLab")
where values == null || values.Contains(lab.datL.Lab_ID)
where reportingPeriod == null || lab.reportingPeriod == reportingPeriod
select lab;
var list = query.ToList<dExp>();
第二种技术:
IEnumerable<dExp> query = ctx.dExp.Include("datLab");
if (values != null)
query = query.Where(lab=>values.Contains(lab.datL.Lab_ID));
if (reportingPeriod != null)
query = query.Where(lab=>lab.reportingPeriod == reportingPeriod);
var list = query.ToList<dExp>();
我们所做的是这样的(l.reportingPeriod == reportPeriod || reportPeriod == null( 因此,您检查该参数是否是其默认值,这意味着它尚未被使用,或者是否有某些内容根据数据库检查它。
在执行查询之前,您需要检查您的值是否为 null,如果是,请不要执行额外的条件。
List<dExp> lstDatExp =
(from l in ctx.dExp.Include("datLab")
where
(values == null || values.Contains(l.datL.Lab_ID)) &&
(reportingPeriod == null || l.reportingPeriod == reportingPeriod)
select l).ToList<dExp>();
这样,如果values
或reportingPeriod
为空,则它们本质上是可选的。