15

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);
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
N K
  • 287
  • 3
  • 11
  • 19

2 Answers2

53

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

Jon
  • 428,835
  • 81
  • 738
  • 806
  • And in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ? – N K Sep 06 '12 at 08:57
  • @user1597284: If `selectedValue` is a `string` then `list2.Contains(selectedValue)`. Take a look at the [`Enumerable`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx) class and all the extension methods it provides. – Jon Sep 06 '12 at 09:04
  • Is there any way to get the value of 's' after finding that 'str' contains 's'? – T-Dog Sep 02 '21 at 11:43
  • @T-Dog sure but you have to specify it better. Like what happens if there are multiple `s`s from the list contained inside `str`? – Jon Sep 03 '21 at 14:02
  • 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. – Jon Sep 03 '21 at 14:09
3

You could use this:

if (myList.Any(x => mystring.Contains(x)))
    // ....
Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
  • And in case, if a dropdown list's selected value equal with an item from the list , how the formulation would be ? – N K Sep 06 '12 at 09:01