当用户搜索时,我无法弄清楚如何处理多个单词。举个例子:搜索:“Blue box”应该可以找到:“One box is blue”。我该怎么做?这基本上就是我的 Controller 看起来像 atm 的样子:
public ActionResult Index(string searchString)
{
var posts = from s in _context.Posts
select s;
var postIndexViewModel = new PostIndexViewModel();
if (!String.IsNullOrEmpty(searchString))
{
posts = posts.Where(s => s.Title.Contains(searchString));
}
// More code here
return View(postIndexViewModel);
}
请您参考如下方法:
你的问题是你正在用整个字符串做包含。这意味着它必须按顺序包含 “Blue box”。
这是你需要做的:
var strings = searchString.Split(' ');
var finalPosts = new List<string>();
if (!String.IsNullOrEmpty(searchString))
{
foreach (var splitString in strings)
{
finalPosts.Add(posts.FirstOrDefault(s => s.Title.Contains(splitString)));
}
}
finalPosts 列表随后包含您的结果。
