仅在传入值时执行Where条件

时间:2013-10-11 14:37:20

标签: c# linq

我在wheredate LabID上有以下LINQ语句。

我正在传递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语句都是可选的?

4 个答案:

答案 0 :(得分:5)

使用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();

答案 1 :(得分:3)

这有两种方法。

但首先,请不要使用单个小写的l作为标识符。很容易将它与数字1混淆。更一般地说,stp使用yr cde中的缩写,它将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>();

答案 2 :(得分:2)

我们做的是像(l.reportingPeriod == reportingPeriod || reportingPeriod == null)所以你检查参数是否是它的默认值意味着它没有被使用过,或者是否有东西在那里检查数据库

答案 3 :(得分:1)

在进行查询之前,您需要检查您的值是否为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>();

这样,如果valuesreportingPeriod为空,则它们基本上是可选的。

相关问题