17

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

2 Answers 2

56

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

Sign up to request clarification or add additional context in comments.

5 Comments

And in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ?
@user1597284: If selectedValue is a string then list2.Contains(selectedValue). Take a look at the Enumerable class and all the extension methods it provides.
Is there any way to get the value of 's' after finding that 'str' contains 's'?
@T-Dog sure but you have to specify it better. Like what happens if there are multiple ss from the list contained inside str?
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.
3

You could use this:

if (myList.Any(x => mystring.Contains(x)))
    // ....

1 Comment

And in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.