Linq-to-SQL reverse contains

2019-09-05 12:34发布

How would I reverse contains in a Linq-to-SQL query so that I can check if Title or Description contain any word from my list, something like:

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

Here is what I have now but that is opposite from what I need.

 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

UPDATE

Now I have

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

but now I get exception on int s = query.Count(); with message "Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator." Does anyone know how to solve it?

4条回答
ら.Afraid
2楼-- · 2019-09-05 12:58

are you looking for something like NOT-IN collection query?

Then this blog post might help

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

HTH

查看更多
Luminary・发光体
3楼-- · 2019-09-05 13:13

my solution is using sub query ( sub select)

  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()
查看更多
等我变得足够好
4楼-- · 2019-09-05 13:14

You want

x => words.Any(w => x.Title.Contains(w) || x.Description.Contains(w))
查看更多
Emotional °昔
5楼-- · 2019-09-05 13:20

Not the most efficient but I managed:

 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)));
   }
查看更多
登录 后发表回答