If condition in LINQ Where clause

前端 未结 8 1990
星月不相逢
星月不相逢 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.

    0 讨论(0)
  • 2020-12-03 07:36

    I'm not sure what the question is, but a possible answer could be:

    Yes,

    list.Where(item => { if (Foo(item)) return true; else return false; });
    

    It would be a complicated way of saying something simple, though.

    0 讨论(0)
提交回复
热议问题