简体   繁体   中英

C# Razor Linq, one generic variable giving unexpected results

Can you please explain this what I am doing wrong here

I am using a search criteria in linq and having this problem while filtering the results that if I used the one generic variable then it doesn't search as expected.

I used separate variable and it worked

Works fine:

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;

Doesn't work when I use the one generic variable:

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;

Also any strategy to make the multiple search more optimized.

I think if you don't use variables is better, you could do something like this

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

This is caused by Closures . In essence the Where clause is bound to the variable and the value of that variable when it is executed is the one used. Since the Where conditions are only evaluated when you enumerate the results this is happening after you have redefined searchCriteria to something else.

Here is a quick code snippet to demonstrate this:

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

Output:

null
foo

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