Reputation: 33
I have the following, where searchby is a string
var products = db.Products
.Where(p => p.Category.Name == category
&& p.Active == true
&& (searchby == null || (searchby != null && p.Keywords.Contains(searchby))))
.Include(p => p.Category)
.OrderBy(p => p.Description)
.ThenBy(p => p.Name);
and would like to change it to allow searchby to contain multiple words which would filter the results to records where Keywords contains all of the words in searchby.
Thanks in advance
Upvotes: 0
Views: 985
Reputation: 460288
You can use another collection and either Enumerable.All
(not sure if supported by your LINQ provider) or !Enumerable.Any
:
List<string> searchby = ... (empty if there is no filter)
var products = db.Products
.Where(p => p.Category.Name == category
&& p.Active == true
&& !searchby.Any(s => !p.Keywords.Contains(s)))
.Include(p => p.Category)
.OrderBy(p => p.Description)
.ThenBy(p => p.Name);
If supported this is more readable:
&& searchby.All(s => p.Keywords.Contains(s)))
Upvotes: 2
Reputation: 4078
This answer assumes, that searchby is either null
or an Array.
Since contains only checks for 1 item, you need to find a way to check for all items within searchby
. The Enumerable.All
-Method comes to mind. Here is the relevant part:
searchby.All(searchItem => p.Keywords.Contains(searchItem))
Upvotes: -1