If condition in LINQ Where clause

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

Can I use if clause with Linq where?

8条回答
  •  死守一世寂寞
    2020-12-03 07:23

    I had a scenario like this where I had to check for null within the list itself. This is what I did.

    items = from p in items
            where p.property1 != null   //Add other if conditions
            select p;
    
    // Use items the way you would use inside the if condition
    

    But as Kelsey pointed out this would work too -

    items = items.Where(a => a.property1 != null);
    

提交回复
热议问题