Reputation: 4323
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?
Upvotes: 1
Views: 2805
Reputation: 1
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()
Upvotes: 0
Reputation: 4323
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)));
}
Upvotes: 1
Reputation: 6882
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
Upvotes: 0
Reputation: 241701
You want
x => words.Any(w => x.Title.Contains(w) || x.Description.Contains(w))
Upvotes: 6