Linq-to-SQL反向包含

时间:2012-06-08 14:53:35

标签: c# linq-to-sql

如何在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();上获得了异常,并显示消息“除了Contains运算符之外,本地序列不能用于查询运算符的LINQ to SQL实现。”有谁知道如何解决它?

4 个答案:

答案 0 :(得分:5)

你想要

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

答案 1 :(得分:1)

效率不高但我管理的是:

 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)));
   }

答案 2 :(得分:0)

你在寻找像NOT-IN集合查询这样的东西吗?

然后这篇博文可能会有所帮助

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

HTH

答案 3 :(得分:0)

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

  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()