如果传入值,则仅执行Where条件 [英] Only do Where condition if a value is passed in
本文介绍了如果传入值,则仅执行Where条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下在date
和LabID
上的where
上执行的LINQ语句.
I have the following LINQ statement that does on where
on the date
and a LabID
.
我要传递LABS和日期的列表,但是不是必需的,并且我可能只传递日期,而没有实验,在这种情况下,我想获得所有实验的结果那个特定的实验室.
I'm passing in a list of LABS and a date, however they are not required, and I could potentially only pass in a date, and no lab, in which case I'd like to get results for all labs for that particular lab.
这是我现在拥有的:
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
语句都是可选的?
But this breaks if the value getting passed in is not there. How do I change this to make sure both of my where
statements are optional?
推荐答案
使用IQueryable,您可以简单地在步骤中添加条件:
With IQueryable you can simply add conditions in steps:
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();
这篇关于如果传入值,则仅执行Where条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文