Home > Backend Development > C++ > How to Use Contains() with a String Array in LINQ Queries?

How to Use Contains() with a String Array in LINQ Queries?

Susan Sarandon
Release: 2024-12-27 07:19:09
Original
125 people have browsed it

How to Use Contains() with a String Array in LINQ Queries?

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

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:

  1. Using a List:

Convert the string[] array into a List and then use the Contains() method on the list:

var uids = new List<string>(stringArray);
var selected = table.Where(t => uids.Contains(t.uid.ToString()));
Copy after login
  1. Using a List (if uid is also an int):

If uid is also an integer, you can convert the string[] array into a List and then use the Contains() method on the list:

var uids = stringArray.Select(int.Parse).ToList();
var selected = table.Where(t => uids.Contains(t.uid));
Copy after login

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);
}
Copy after login

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()));
Copy after login

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!

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