简体   繁体   English

重构LINQ查询

[英]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 ) 可以看出,这两个查询之间的唯一区别仅在于属性名称(第一个是Property1 ,第二个是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? 有没有更好的方法在结构化的mannner中重构/编写代码(一些常见的方法,只传递属性名称,并按照那样过滤记录)或者这是做同样的正确方法?

Need help. 需要帮忙。

Thanks 谢谢

It is also possible to add an inline if in the where clause 如果在where子句中也可以添加内联

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. 您可以在if语句中链接命令。 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: 或者甚至只是在你的orignal代码中写出更整洁的lambda结构:

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 吉姆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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