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)))
// ....
Author by
N K
Updated on June 16, 2022Comments
-
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 over 11 yearsAnd in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ?
-
N K over 11 yearsAnd in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ?
-
Waihon Yew over 11 years@user1597284: If
selectedValue
is astring
thenlist2.Contains(selectedValue)
. Take a look at theEnumerable
class and all the extension methods it provides. -
T-Dog over 2 yearsIs there any way to get the value of 's' after finding that 'str' contains 's'?
-
Waihon Yew over 2 years@T-Dog sure but you have to specify it better. Like what happens if there are multiple
s
s from the list contained insidestr
? -
Waihon Yew over 2 yearsFor example, if you replace
Any
withFirstOrDefault
, the return value is going to be the firsts
that is contained instr
ornull
if no such string exists in the list.