C#Razor Linq,一个提供意外结果的通用变量

时间:2019-02-12 17:00:27

标签: c# linq razor model-view-controller

能请您解释一下我在这里做错了什么

我在linq中使用搜索条件,并且在过滤结果时遇到了这个问题,如果我使用一个泛型变量,那么它将无法按预期进行搜索。

我使用了单独的变量,它起作用了

工作正常:

string city = Request.QueryString["city"];
properties = (Request.QueryString["city"] != null) ? properties.Where(x => x.City == city) : properties;

string pType = Request.QueryString["propertytype"];
properties = (Request.QueryString["propertytype"] != null) ? properties.Where(x => x.PropertyType == pType) : properties;

使用一个通用变量时不起作用:

string searchCriteria = Request.QueryString["city"];
properties = (Request.QueryString["city"] != null) ? properties.Where(x => x.City == searchCriteria) : properties;

searchCriteria= Request.QueryString["propertytype"];
properties = (Request.QueryString["propertytype"] != null) ? properties.Where(x => x.PropertyType == searchCriteria) : properties;

还有使多重搜索更加优化的任何策略。

2 个答案:

答案 0 :(得分:0)

我认为如果您不使用变量会更好,那么您可以做类似的事情

if(!string.IsNullOrEmpty(Request.QueryString["city"]))
{
   properties =properties.Where(x => x.City == Request.QueryString["city"]);
}


if(!string.IsNullOrEmpty(Request.QueryString["propertytype"]))
{
   properties = properties.Where(x => x.PropertyType == Request.QueryString["propertytype"])
}

答案 1 :(得分:0)

这是由Closures引起的。本质上,Where子句绑定到变量,并且在执行该变量时使用该变量的值。由于仅在枚举结果时才评估Where条件,因此在将searchCriteria重新定义为其他值之后,就会发生这种情况。

下面是一个简短的代码片段来演示这一点:

var list = new List<string>() {"foo", "bar", "bang"};
string parameter = "wibble";
var results = list.Where(x=>x==parameter);
Console.WriteLine(results.FirstOrDefault()??"null");
parameter = "foo";
Console.WriteLine(results.FirstOrDefault()??"null");

输出:

  


  foo