简体   繁体   中英

C# Linq multi-word search

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

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

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

Source

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