How to Replace Contains(string) with Contains(string[]) in LINQ Queries
In LINQ, the Contains() method can be used to check if a collection contains a specific element. By default, the Contains() method takes a single string parameter, but what if you need to compare against an array of strings?
Question:
I have a LINQ query that looks like this:
from xx in table where xx.uid.ToString().Contains(string[]) select xx
The values in the string[] array are numbers (e.g., 1, 45, 20, 10). I want to use the Contains() method to check if the xx.uid property (which is a number) is present in the array. How can I do this?
Answer:
To compare xx.uid against an array of strings, you cannot directly use the Contains(string) method. Instead, you need to convert the string[] array into a collection that supports the Contains() method. Here are two approaches:
Convert the string[] array into a List
var uids = new List<string>(stringArray); var selected = table.Where(t => uids.Contains(t.uid.ToString()));
If uid is also an integer, you can convert the string[] array into a List
var uids = stringArray.Select(int.Parse).ToList(); var selected = table.Where(t => uids.Contains(t.uid));
Extension Method (Optional):
You can also create an extension method for the string[] type to provide a Contains() method that takes a string argument:
public static bool Contains(this string[] arr, string value) { return arr.Any(s => s == value); }
With this extension method, you can directly use the Contains() method on the string[] array:
var selected = table.Where(t => stringArray.Contains(t.uid.ToString()));
The above is the detailed content of How to Use Contains() with a String Array in LINQ Queries?. For more information, please follow other related articles on the PHP Chinese website!