If condition in LINQ Where clause

Viewed 111659

With Linq, can I use a conditional statement inside of a Where extension method?

8 Answers

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);
from item in items
where condition1
&& (condition2 ? true : condition3)
select item

This is how can you can do it with the noob Linq syntax. This applies the condition3 only if condition2 is false. If condition2 is true, you are essentially doing && true which has no effect on the where clause.

So it is essentially doing this:

if(condition2)
{
    from item in items
    where condition1
    select item
else
{
    from item in items
    where condition1
    && condition3
    select item
}
Related