我有一个Of Of Of List和id,想查询带有多个参数的列表,以减少搜索页面上的结果。
int SecLink = (!string.IsNullOrEmpty(Request.QueryString["Sector"])) ? Convert.ToInt32(Request.QueryString["Sector"]) : 0;
int LocLink = (!string.IsNullOrEmpty(Request.QueryString["Location"])) ? Convert.ToInt32(Request.QueryString["Location"]) : 0;
int IndLink = (!string.IsNullOrEmpty(Request.QueryString["Industry"])) ? Convert.ToInt32(Request.QueryString["Industry"]) : 0;
int VacLink = (!string.IsNullOrEmpty(Request.QueryString["Vacancy"])) ? Convert.ToInt32(Request.QueryString["Vacancy"]) : 0;
string keyword = Request.QueryString["SearchTerm"];
var dx = new DataX();
var lstJobs = dx.GetAllJobs().Where(x => x.SectorLink.Equals(SecLink) && x.LocationLink.Equals(LocLink) && x.IndustryLink.Equals(IndLink) && x.VacancyTypeLink.Equals(VacLink) && x.JobName.Contains(keyword)).ToList();
if (lstJobs.Count > 0)
{
uiRptSearchJobs.DataSource = lstJobs;
uiRptSearchJobs.DataBind();
uiLitSearchResults.Text = string.Format("<h4>Search result found {0} matches</h4>", lstJobs.Count);
}
搜索参数可能是&#39; 0&#39;由于没有从上一页中选择,所以结果应该反映他的。
这是我传递的查询字符串:
Default.aspx?section=search&Sector=4&Location=0&Industry=0&Vacancy=0&SearchTerm=
但正如您所看到的,它们的查询字符串将随用户从上一页中选择的内容而改变。
答案 0 :(得分:7)
如果我理解正确,如果参数值为0,您不想过滤?如果是这样,有两个解决方案:
检查条件中参数是否等于0:
var lstJobs = dx.GetAllJobs().Where(x =>
(SecLink == 0 || x.SectorLink.Equals(SecLink))
&& (LocLink == 0 || x.LocationLink.Equals(LocLink))
&& (IndLink == 0 || x.IndustryLink.Equals(IndLink))
&& (VacLink == 0 || x.VacancyTypeLink.Equals(VacLink))
&& x.JobName.Contains(keyword)).ToList();
Linq善良,动态构建您的查询:
var query = dx.GetAllJobs().Where(x => x.JobName.Contains(keyword));
if (SecLink != 0)
{
query = query.Where(x => x.SectorLink.Equals(SecLink));
}
if (LocLink != 0)
{
query = query.Where(x => x.LocationLink.Equals(LocLink));
}
if (IndLink != 0)
{
query = query.Where(x => x.IndustryLink.Equals(IndLink));
}
if (VacLink != 0)
{
query = query.Where(x => x.VacancyTypeLink.Equals(VacLink));
}
var lstJobs = query.ToList();
答案 1 :(得分:3)
一种选择是有条件地执行Where
条款:
如果搜索字词应该一起进行AND运算:
var lstJobs = dx.GetAllJobs();
if (SecLink > 0)
lstJobs = lstJobs.Where(x => x.SectorLink.Equals(SecLink))
if (LocLink > 0)
lstJobs = lstJobs.Where(x => x.LocationLink.Equals(LocLink))
if (IndLink > 0)
lstJobs = lstJobs.Where(x => x.IndustryLink.Equals(IndLink))
if (VacLink > 0)
lstJobs = lstJobs.Where(x => x.VacationLink.Equals(VacLink))
// Performance does not suffer because the query will
// not get evaluated until it's required. For example,
// here we call .ToList, which forces the query to be evaluated.
var result = lstJobs.ToList();
但是,您已明确表示您需要将搜索字词ORed放在一起。在那种情况下:
var lstJobs = dx.GetAllJobs().Where(x => x.JobName.Contains(keyword));
if (SecLink > 0)
lstJobs = lstJobs.Union(
dx.GetAllJobs().Where(x => x.SectorLink.Equals(SecLink))
if (LocLink > 0)
lstJobs = lstJobs.Union(
dx.GetAllJobs().Where(x => x.LocationLink.Equals(LocLink))
etc...