If condition in LINQ Where clause

前端 未结 8 2011
星月不相逢
星月不相逢 2020-12-03 06:56

Can I use if clause with Linq where?

8条回答
  •  遥遥无期
    2020-12-03 07:25

    Not sure if this is appropriate but it is quite useful, you can use ifs quite handily with conditional where clauses:

     var r = (from p in productinfo.tblproduct
                         where p.Accountid == accountid
                         select p);
    
                if (uuf1 != null)
                    r = r.Where(p => p.UnitUserField1 == uuf1);
    
                if (uuf2!= null)
                    r = r.Where(p => p.UnitUserField2 == uuf2);
    

    So the where clause will be amended according to what is in UUF1 or UUF2 i.e. you might have only UUF1 with info, in which case it will take that and ignore the UUF2 where clause, you might have both in which it will take both or you might not have anything in UUF1 or 2 and your where clause will just take the accountid as the where clause.

提交回复
热议问题