首页 > 解决方案 > C# Razor Linq,一个产生意外结果的通用变量

问题描述

你能解释一下我在这里做错了什么吗

我在 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;

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

标签: c#linqrazormodel-view-controller

解决方案


我认为如果你不使用变量会更好,你可以做这样的事情

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

推荐阅读