score:5

Accepted answer

It is also possible to add an inline if in the where clause

lstItem.ItemsSource = 
     (from item in Items
      where (test == "S" ? item.Property1 == "SomeValue" : item.Property2 == "SomeOtherValue")
      select item);

score:4

You can chain your commands within if statements. E.g.:

var items = from item in Items 
            select item; 

if(type== "S")  
{     
   items = items.Where(item => item.Property1 == "SomeValue");
}  
else  
{  
   items = items.Where(item => item.Property2 == "SomeOtherValue");
}  

Or even just write the tidier lambda structure in you orignal code:

if(type== "S") 
{    
    lstItem.ItemsSource = Items.Where(item => item.Property1 == "SomeValue");
} 
else 
{ 
    lstItem.ItemsSource = Items.Where(item.Property2 == "SomeOtherValue");
}

score:2

well, you could start by boiling the expression down to:

Func<Items, bool> expr;

if(type== "S")  
{ 
    expr = (item => item.Property1 == "SomeValue");
}
else
{
    expr = (item => item.Property2 == "SomeOtherValue");
}

var items = Items.Where(expr);

of course, the game plan is really to make it all a single statemnet, but this makes it a LITTLE more manageable i think :)

jim

score:3

I like:

lstItem.ItemsSource = Items.Where(type == "S" ? 
                 item => item.Property1 == "SomeValue":
                 item => item.Property2 == "SomeOtherValue");

Related Articles