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); }
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;
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!