0

我有一个连接到数据库的相当简单的 MVC webapp。用户需要一个可以从单个表中提取某些记录的搜索页面。用户可以给出 1 个或多个关键字。搜索功能必须在 3 个不同的列中搜索包含这些关键字的记录:标题、描述或 poc。

我有以下设置,但它不正确。它提供包含任何关键字的记录。结果必须是包含所有关键字的记录。另外,我不确定这是否是编写搜索功能的最佳方式......

// searchString contains all keywords delimited by spaces
string[] keywordArray = Regex.Split(searchString, "\\s");

var model = new List<MyTable>();
foreach (string word in keywordArray)
{
   foreach (var record in myTableRepository.MyTable.Where(x => x.title.ToLower().Contains(word.ToLower()) || (x.description != null && x.description.ToLower().Contains(word.ToLower())) || (x.poc != null && x.poc.ToLower().Contains(word.ToLower()))).ToList())
   {
       model.Add(new MyTable
       {
          id = record.id,
          title = record.title,
          description = record.description, 
          poc = record.poc
       });
   }
}
return View(model);

例如,如果用户给出以下搜索条件“john test phase”,那么结果可能如下所示:

title                   description                  poc
Lorem Ipsum Test A      Phase A lorem ipsum          john doe
Lorem Ipsum phase       This is john test for jack   jane doe
Lorem Ipsum             John test for jim            clark phase

ETC..

提前感谢您的建议和提示!

4

1 回答 1

1

一次搜索一条记录并检查一条记录中的所有关键字可能会更好。也许您可以在一个变量中收集与特定条目相关联的所有单词,然后在该变量中搜索所有关键字。

// searchString contains all keywords delimited by spaces
string[] keywordArray = Regex.Split(searchString, "\\s");

var model = new List<MyTable>();
Boolean searchResult;
foreach (var record in myTableRepository.MyTable)
{
    searchResult = true;

    var recordTerms = record.title + " " + record.description + " " + record.poc;
    recordTerms = recordTerms.toLower();
    recordArray = Regex.Split(recordTerms, "\\s");

    foreach (var word in keywordArray)
    {
        if (!recordArray.asList.contains(word))
            searchResult = false;
        }
    }

    if (searchResult) {
        model.Add(new MyTable
        {
            id = record.id,
            title = record.title,
            description = record.description, 
            poc = record.poc
        });
    }
}
return View(model);
于 2013-05-17T00:52:13.333 回答