简体   繁体   中英

Linq-to-SQL reverse contains

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?

你要

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM