Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains any element of a List<string>?

I have an if statement, where I would like to check, if a string contains any item of a list<string>.

if (str.Contains(list2.Any()) && str.Contains(ddl_language.SelectedValue))
{
    lstpdfList.Items.Add(str);
}
like image 410
N K Avatar asked Sep 06 '12 08:09

N K


People also ask

How do you check if a string contains something from a list?

Using any() to check if string contains element from list. Using any function is the most classical way in which you can perform this task and also efficiently. This function checks for match in string with match of each element of list.

How do you check if a string contains all elements from a list in Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count() function.

How do you check if a string contains an element from a list Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you check if a list of strings is in a string?

You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any .


2 Answers

The correct formulation is

list2.Any(s => str.Contains(s))

This is read as "does list2 include any string s such that str contains s?".

like image 180
Jon Avatar answered Sep 23 '22 02:09

Jon


You could use this:

if (myList.Any(x => mystring.Contains(x)))
    // ....
like image 25
Dan Puzey Avatar answered Sep 21 '22 02:09

Dan Puzey