Lambda/LINQ combines Contains conditions for multi-keyword search
In many database operations, it is often necessary to search for specific keywords in text fields. This usually involves using the LIKE operator in SQL, for example:
<code class="language-sql">SELECT * FROM MainList WHERE Comment LIKE '%keyword1%' OR Comment LIKE '%keyword2%'</code>
This query searches each keyword separately, resulting in a complex query containing multiple LIKE clauses. To perform a similar search using Lambda/LINQ in C#, you need to consider the following scenario:
Known conditions:
Expected results:
The solution utilizes an extension method called FilterByItems:
<code class="language-csharp">var newList = MainList .FilterByItems(keywords, (m, k) => m.Comments.Contains(k), true) .ToList();</code>
FilterByItems method accepts the following parameters:
This method replaces the placeholder parameters in the filterPattern expression with each keyword in the items list. The generated predicate is then used to filter the MainList.
The ExpressionReplacer class handles parameter replacement in predicates. It replaces placeholder parameters with actual keyword values.
This approach allows for efficient searching of multiple keywords in one query, reducing the need for multiple LIKE clauses and simplifying SQL statements.
The above is the detailed content of How to Efficiently Search for Multiple Keywords in a List Using Lambda/LINQ?. For more information, please follow other related articles on the PHP Chinese website!