LINQ从字符串数组中包含一个匹配项
本文关键字:包含一 字符串 数组 LINQ | 更新日期: 2023-09-27 18:08:22
让这个工作有困难:
/// <summary>
/// Retrieve search suggestions from previous searches
/// </summary>
public static string[] getSearchSuggestions(int SectionID, string Query)
{
string[] Suggestions;
string[] Words = Query.Split(' ');
using (MainContext db = new MainContext())
{
Suggestions = (from c in db.tblSearches
where c.SectionID == SectionID &&
Words.Any(w => c.Term.Contains(w))
select c.Term).ToArray();
}
return Suggestions;
}
我:
系统。NotSupportedException:本地序列不能用于LINQ to SQL查询操作符的实现,除了包含操作符。
我想返回字段c.Term
包含Words
数组中的任何单词的记录。我还想按比赛总数排序,但这似乎很难做到!我找到了这个MSDN。但是我也不能让它和我的查询一起工作。
好了,在仔细研究之后,我意识到问题不在于Any或Contains。Linq to SQL不喜欢您将本地序列(单词)与SQL集合(db.tblSearches)组合在一起。因此,为了实现这一点,您必须将其分解为两个单独的查询。
public static string[] getSearchSuggestions(int SectionID, string Query)
{
string[] Suggestions;
string[] Words = Query.Split(' ');
using (MainContext db = new MainContext())
{
string[] all = (from c in db.tblSearches
where c.SectionID == SectionID
select c.Term).ToArray();
Suggestions = (from a in all
from w in Words
where a.Contains(w)
select a).Distinct().ToArray();
}
return Suggestions;
}
请记住,在第二个查询中,Contains
是区分大小写的,因此您可能必须添加一个不区分大小写的扩展方法,或者采用老派方法并将它们替换为.ToUpper()
。我在4.0中对我的一个上下文运行了这个,它正确地返回了所有88个字符串(可能有9814个)。虽然这是一个彻底的PITA。这个问题肯定是+1。
在最终答案中加入.Distinct()
首先将数组转换为列表,
List<string> wordList = Words.ToList();
然后修改linq查询,如下所示:
Suggestions = (from c in db.tblSearches
where c.SectionID == SectionID &&
Words.Contains(c.Term)
select c.Term).ToArray();
我想我明白你的问题了。在您的原始查询中,您正在使用c.Term.Contains()…Contains是一个扩展方法,需要在实现Enumerable的对象上调用,因此您不能在从数据库调用返回的字段上调用它。这就是为什么另一个回答你问题的用户说你需要在你的Contains中翻转东西,因为它永远不会让你调用c.Terms
您需要更改Contains子句的顺序:
Suggestions = (from c in db.tblSearches
where c.SectionID == SectionID &&
Words.Contains(w => c.Term)
select c.Term).ToArray();