我有3个复选框,我将用于搜索选项。现在,用户可以选择任意数量的搜索。我的问题是:Is there a more convenient way to write out the logic for the search, rather than doing an if/else or boolean check for for every combination?
3个复选框也不错,但我可以看到5+复选框的问题。是否有更好的方法来实现具有多个选项的搜索功能?
这就是我目前正在做的事情:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string searchFilter)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "year" : "";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
ViewBag.CurrentFilterSelection = searchFilter;
var resolutions = from c in db.AllResolutions select c;
if (!String.IsNullOrEmpty(searchString))
{
resolutions = resolutions.Where(c => c.ResolutionYear.Contains(searchString) || c.ResolutionTextShort.Contains(searchString) || c.ResDescription.Contains(searchString));
}
switch (sortOrder)
{
case "date":
resolutions = resolutions.OrderByDescending(c => c.ResDate);
break;
case "year":
resolutions = resolutions.OrderByDescending(c => c.ResolutionYear);
break;
case "number":
resolutions = resolutions.OrderByDescending(c => c.ResolutionNumber);
break;
default:
resolutions = resolutions.OrderBy(c => c.ResolutionYear).ThenBy(c => c.ResolutionNumber);
break;
}
int pageSize = 25;
int pageNumber = (page ?? 1);
return View(resolutions.ToPagedList(pageNumber, pageSize));
}
我目前正在3个单独的列中搜索数据库,并返回包含searchString
的结果。我希望能够让用户选择是否要限制他们搜索的列
ie: I want to search for all 2018 resolutions or I want to search all 2018 resolutions with the keyword here
答案 0 :(得分:1)
我认为最明确的方法就是这样:
if(searchForYear)
{
resolutions = resolutions.Where(c => c.ResolutionYear.Contains(searchString));
}
if (searchForTextShort)
{
resolutions = resolutions.Where(c => c.ResolutionTextShort.Contains(searchString));
}
//and so on for each other checkbox value
所以基本上:是的,唯一的方法是"列表" " ifs"但您可以像上面那样拆分查询构建,这样代码仍然可读且易于维护