Reputation: 18684
I am trying to write a LINQ query that searches for a list of records, which has 1 or more keywords in the text.
It gets complicated by the fact that I source the keywords from a table, and each keyword has an OPTIONAL category id.
So, what I am asking for my query is, give me all the rows in the table, where the title has AT LEAST ONE (i.e. Not ALL) of the keywords, and if the keyword has an associated category id, then the row must be part of that category too.
var reply = new List<RssFeedItemDto>();
// Get the keywords and categories of interest
var words = (from c in entities.site_user_keyword where c.site_user_id == loggedInUserId select c).ToList();
// Main query
var items = (from c in entities.rss_feed_item select c);
// Filter items.
foreach(var c in words)
{
items = items.Where(x => x.title.Contains(c.word));
//if(c.rss_feed_category_id.HasValue)
//{
// items = items.Where(x => x.rss_feed.rss_feed_category_id == c.rss_feed_category_id);
//}
}
So, words is a list of keywords, and an optioncal CategoryId.
I then needs to search the rss table, where the title contains one of the keywords. At the moment, the way I am doing it, it's doing an AND.
So, the sql produced may look like:
SELECT * FROM table
WHERE title LIKE '%crash%'
AND title LIKE '%mars%'
But what I want is:
SELECT * FROM table
WHERE title LIKE '%crash%'
OR title LIKE '%mars%'
How can I change this into an OR.
Upvotes: 0
Views: 85
Reputation: 29836
Here you go:
var words = entities.site_user_keyword.Where(c => c.site_user_id == loggedInUserId).ToList();
var items = entities.rss_feed_item.Where(item => words.Any(word => item.title.Contains(word));
Upvotes: 1