Only do Where condition if a value is passed in

后端 未结 4 520
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  猫巷女王i
    2021-01-24 06:47

    Here are two ways to do that.

    But first, please don't use a single lowercase l as an identifier. It is way too easy to confuse it with the number 1. More generally, stp using abbrevs in yr cde, it mks it hrdr to rd.

    First technique:

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

    Second technique:

    IEnumerable 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();
    

提交回复
热议问题