Linq with String Array包含

时间:2015-07-01 09:03:16

标签: c# arrays linq linq-to-sql

我有一个字符串数组项目&一个数据库对象列表,我想从中做一个选择查询

List<string> target_terms = new List<string> { "car", "mechanic" }

if (isNotExactPhrase)
{
    List<int> _tagIds = (from item in dbContext.Tags
                    where target_terms.Any(w => item.TagName.Contains(w))
                    select item.TagId).ToList();
}

我想要所有带有数组的标签

我必须使用2个选项我要检查标记名包含任何关键字&amp; 如果搜索是精确短语,那么我想检查任何Tagname ==任何关键字

但对于此查询,我收到错误

  

本地序列不能用于查询的LINQ to SQL实现   除Contains运算符之外的运算符。

如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

尝试此查询

var _tagIds = (from item in dbContext.Tags
                    where keywords.contains(item.TagName)
                    select item.TagId).ToList();

没有直接的等价物,但有些方法的工作方式相似,具体取决于模式。

string.Contains(&#34; pattern&#34;)相当于LIKE&#39;%pattern%&#39;

string.StartsWith(&#34; pattern&#34;)相当于LIKE&#39; pattern%&#39;

string.EndsWith(&#34; pattern&#34;)相当于LIKE&#39;%pattern&#39;

答案 1 :(得分:1)

After hitting this problem a multitude of times, I created a nuget package that solves this common issue.

Using NinjaNye.SearchExtensions you can do the following:

var _tagIds = dbContext.Tags.Search(t => t.TagName)
                            .Containing(keywords)
                            .Select(t => t.TagId)
                            .ToList();

If you needed to you could also search against multiple properties and return records where a match was found in either property.

var _tagIds = dbContext.Tags.Search(t => t.TagName, t => t.Description)
                            .Containing(keywords)
                            .Select(t => t.TagId)
                            .ToList();

Hope this helps

答案 2 :(得分:-1)

尝试将Any替换为contains

List<int> _tagIds = (from item in dbContext.Tags
                    where target_terms.Contains(w => item.TagName.Contains(w))
                    select item.TagId).ToList();