0

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • 1
    Could you please elaborate on this bit -- "it doesn't search as expected" – Fabjan Feb 12 '19 at 17:04
  • It may be to do with closures. The `searchCriteria` in the where clause may only be evaluated when you actually enumerate it which is after you have redefined searchCriteria to mean something else. – Chris Feb 12 '19 at 17:38

2 Answers2

0

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"])
}
  • LINQ to Entities does not recognize the method 'System.String get_Item(System.String)' method, and this method cannot be translated into a store expression. – Rizwan Ali Feb 13 '19 at 22:09
0

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

Chris
  • 27,210
  • 6
  • 71
  • 92