仅在传入值时执行Where条件

Mad*_* Zu 1 c# linq

我有以下LINQ语句wheredate和a上执行LabID.

我正在传递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>();
Run Code Online (Sandbox Code Playgroud)

但如果传入的值不存在则会中断.如何更改此选项以确保我的两个where语句都是可选的?

Hen*_*man 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();
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个更清洁然后我忘了这样做. (2认同)