LINQ Query Refactoring

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

How can you understand that the only difference between these two queries relates only to the name of the property (for the first it is Property1 , and for the second it is Property2 )

Is there a better way to refactor / write code in a structured mannner (some general method in which only the property name will be passed and the record will be filtered out accordingly), or is this the right way to do the same

Help is needed.

thank

+3
source share
4 answers

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);
+5
source

if. :.

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

- orignal:

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

:

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

, :

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 really should do all one statemnet, but this makes LITTLE more manageable, I think :)

Jim

+2
source

Source: https://habr.com/ru/post/1760262/


All Articles