Home > Backend Development > C++ > How to Efficiently Search for Multiple Keywords in a List Using Lambda/LINQ?

How to Efficiently Search for Multiple Keywords in a List Using Lambda/LINQ?

Susan Sarandon
Release: 2025-01-21 11:56:09
Original
501 people have browsed it

How to Efficiently Search for Multiple Keywords in a List Using Lambda/LINQ?

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>
Copy after login

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:

  • MainList: List containing Comments field
  • keywords: list of keywords to search

Expected results:

  • A new list containing records whose Comments field in MainList contains any keyword in the keywords list.

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>
Copy after login

FilterByItems method accepts the following parameters:

  • items: list of keywords to search
  • filterPattern: an expression used to check whether a record contains a specific keyword
  • isOr: a flag indicating whether to use the OR or AND operator to combine predicates (default is OR)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template