Home > Backend Development > C++ > How to Use LINQ Contains with a String Array Instead of a Single String?

How to Use LINQ Contains with a String Array Instead of a Single String?

Patricia Arquette
Release: 2024-12-28 04:52:14
Original
462 people have browsed it

How to Use LINQ Contains with a String Array Instead of a Single String?

Using LINQ Contains(string[]) Instead of Contains(string)

In LINQ queries, the Contains operator is used to check if a specific value exists within a collection. By default, Contains accepts a single string as its parameter. However, some scenarios may require comparing multiple values from a string array.

To address this, you can create a custom extension method for string[] that allows it to be used with the Contains operator.

Custom Extension Method:

public static bool ContainsArray(this string[] array, string value)
{
    return array.Any(element => element == value);
}
Copy after login

This method iterates through the string array and returns true if the specified value is found, or false otherwise.

Usage in LINQ Query:

With the extension method defined, you can now use it in your LINQ query:

var uids = new[] { "1", "45", "20", "10" };
var query = from xx in table
            where xx.uid.ToString().ContainsArray(uids)
            select xx;
Copy after login

By using the ContainsArray extension method, you can now compare the value of xx.uid with multiple values from the uids string array. The query will return all entities where xx.uid is contained within the specified array.

The above is the detailed content of How to Use LINQ Contains with a String Array Instead of a Single String?. 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