Linq-to-SQL 反向包含

本文关键字:包含 Linq-to-SQL | 更新日期: 2023-09-27 18:36:31

我将如何在Linq-to-SQL查询中反向包含,以便我可以检查TitleDescription是否包含列表中的任何单词,如下所示:

var query = context.Shapes.Where(x => x.Title.Contains(words));

这是我现在拥有的,但这与我需要的相反。

 List<string> words = Search.GetTags(q);
 //words = round,circle,square
 using(ShapesDataContext context = new ShapesDataContext())
 {
    var query = context.Shapes.Where(x => words.Contains(x.Title) || 
    words.Contains(x.Description));
 }
// Item 1: Title = Elipse , Decsription = This is not round circle
//This should be a match! but words doesn't contain 
//"This is not round circle", only round and circle so no match

更新

现在我有

  var query = context.Shapes.Where(x => words.Any(w => x.Title.Contains(w) || x.Description.Contains(w)))
  int s = query.Count();

但现在我在int s = query.Count();收到异常,并显示消息"本地序列不能在查询运算符的 LINQ to SQL 实现中使用,但包含运算符除外。有谁知道如何解决它?

Linq-to-SQL 反向包含

你想要

x => words.Any(w => x.Title.Contains(w) || x.Description.Contains(w))

不是最有效的,但我设法:

 List<string> words = Search.GetTags(q);
 using(ShapesDataContext context = new ShapesDataContext())
 {
   IQueryable<Shape> query = Enumerable.Empty<Shape>().AsQueryable();
   foreach (var word in words)
   {
     query = query.Union(context.Shapes.Where(x => x.Title.Contains(word) || x.Description.Contains(word)));
   }

您是否正在寻找类似 NOT-IN 集合查询的内容?

那么这篇博文可能会有所帮助

http://introducinglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx

我的解决方案是使用子查询(子选择)

  dim searchTerms as new list of(string) 'search terms here
  dim Result = (From x In DB.items Where 
                    (
                      searchTerms.Count = 0 Or
                      (From z In searchTerms Where x.SearchableText.Contains(z) Select z).Count > 0
                    )
                    Select x).ToList()