tags:

views:

83

answers:

4

Consider the below

if(type== "S")
{   
    lstItem.ItemsSource = (from item in Items
              where item.Property1 == "SomeValue"
              select item);
}
else
{
    lstItem.ItemsSource = (from item in Items
              where item.Property2 == "SomeOtherValue"
              select item);
}

As can be figured out that the only difference between these two queries is only in the property name (for the first one it is Property1 & for the second it is Property2)

Is there any better way of refactoring / writing the code in a structured mannner(some common method where only the property name will be passed and the record will be filtered as per that) or this is the proper way of doing the same?

Need help.

Thanks

+5  A: 

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");
}
ck
Why do you need `items` at all? Why not perform `.Where(...)` directly on `Items`?
stakx
@stakx - already thought of that - check the edit. The first would be good if there was a common filter.
ck
+3  A: 

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

jim
+5  A: 

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);
Wouter Janssens - Xelos bvba
+3  A: 

I like:

lstItem.ItemsSource = Items.Where(type == "S" ? 
                 item => item.Property1 == "SomeValue":
                 item => item.Property2 == "SomeOtherValue");
Archeg
Oops, Wouter was the first one)
Archeg
I still gave you a point for the correct answer anyways! :)
C Johnson