简体   繁体   中英

Refactoring LINQ query

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

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);

You can chain your commands within if statements. Eg:

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");
}

I like:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM