使用 Linq to Entities 到 Return 匹配可能字符串列表的记录

Using Linq to Entities to Return Records that Match a List of Possible Strings

我有 table 的东西。这些 Somethings 有一个 Name 字段。我网站的用户可以输入该名称的前向或后向组合,我需要 return 正确的内容。

示例:

用户输入:"name the".

我有 Something.Name 个 "the name"。

我return那个东西

现在,SQL 看起来像这样:

SELECT * FROM Somethings
Where Name LIKE '%name the%'
OR Name LIKE '%the name%'

如您所见,我需要获取用户输入的字符串的所有排列,然后搜索每一个。我尝试使用 Linq to Entities 循环执行此操作,如下所示:

var string[] arr = {"name the", "the name"};

foreach (var str in arr)
{
    var matchingSomethings = db.Somethings
                .Where(e => e.Name.IndexOf(str , StringComparison.InvariantCultureIgnoreCase) >= 0);
}

当用户输入两个词时,这非常有效。但是,对于五个单词(120 个排列),它变得很麻烦并且用户查询超时。

然后我尝试了:

var matchingSomethings = db.Somethings
                .Where(e => arr.Contains(e.Name));

您可以清楚地看到那里的明显缺陷,即名称为 "the name of the Something" 的某物不会在此查询中匹配,因为该名称未包含在用户输入的片段中"the name"。

那么我将如何编写 Linq to Entities 查询来获取所有可能的 Somethings,其中用户输入的片段的任何排列都包含在 Something 的名称中?

单独查找每个单词,然后 return 查找包含所有匹配单词的项目。应该这样做:

public void MatchSomethings(string input)
{
    var data = new List<something>();
    var wordsInName = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    var match = data.Where(s => wordsInName.All(word => s.Name.Contains(word)));
}