Using C# to check if string contains a string in string array

Theomax picture Theomax · May 26, 2010 · Viewed 611k times · Source

I want to use C# to check if a string value contains a word in a string array. For example,

string stringToCheck = "text1text2text3";

string[] stringArray = { "text1", "someothertext", etc... };

if(stringToCheck.contains stringArray) //one of the items?
{

}

How can I check if the string value for 'stringToCheck' contains a word in the array?

Answer

Anton Gogolev picture Anton Gogolev · May 26, 2010

Here's how:

if(stringArray.Any(stringToCheck.Contains))
/* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */

This checks if stringToCheck contains any one of substrings from stringArray. If you want to ensure that it contains all the substrings, change Any to All:

if(stringArray.All(stringToCheck.Contains))