Only do Where condition if a value is passed in

后端 未结 4 514
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 06:22

I have the following LINQ statement that does on where on the date and a LabID.

I\'m passing in a list of LABS and a date, however

4条回答
  •  鱼传尺愫
    2021-01-24 07:02

    With IQueryable you can simply add conditions in steps:

    int? reportingPeriod = ...;
    
    IQueryable 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 results = resultsQuery.ToList();
    

提交回复
热议问题