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

12,200

Solution 1

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?".

Solution 2

You could use this:

if (myList.Any(x => mystring.Contains(x)))
    // ....
Share:
12,200
N K
Author by

N K

Updated on June 16, 2022

Comments

  • N K
    N K almost 2 years

    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);
    }
    
  • N K
    N K over 11 years
    And in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ?
  • N K
    N K over 11 years
    And in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ?
  • Waihon Yew
    Waihon Yew over 11 years
    @user1597284: If selectedValue is a string then list2.Contains(selectedValue). Take a look at the Enumerable class and all the extension methods it provides.
  • T-Dog
    T-Dog over 2 years
    Is there any way to get the value of 's' after finding that 'str' contains 's'?
  • Waihon Yew
    Waihon Yew over 2 years
    @T-Dog sure but you have to specify it better. Like what happens if there are multiple ss from the list contained inside str?
  • Waihon Yew
    Waihon Yew over 2 years
    For example, if you replace Any with FirstOrDefault, the return value is going to be the first s that is contained in str or null if no such string exists in the list.