简体   繁体   English

C#Linq多字搜索

[英]C# Linq multi-word search

I have the following, where searchby is a string 我有以下内容,其中searchby是一个字符串

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. 并希望对其进行更改以允许searchby包含多个单词,这些单词将过滤结果到记录中,其中关键字包含searchby中的所有单词。

Thanks in advance 提前致谢

You can use another collection and either Enumerable.All (not sure if supported by your LINQ provider) or !Enumerable.Any : 您可以使用另一个集合,也可以使用Enumerable.All (不确定您的LINQ提供程序是否支持)或!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. 该答案假定searchby为null或Array。

Since contains only checks for 1 item, you need to find a way to check for all items within searchby . 由于只包含一项检查,因此您需要找到一种方法来检查searchby所有项目。 The Enumerable.All -Method comes to mind. 我想到了Enumerable.All -Method。 Here is the relevant part: 这是相关的部分:

searchby.All(searchItem => p.Keywords.Contains(searchItem))

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM