Linq-to-SQL reverse contains

2019-09-05 12:44发布

问题:

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?

回答1:

You want

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


回答2:

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


回答3:

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



回答4:

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