Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# if string contains more than 1 value

Good Morning,

In an if statement if we want to check if a string contains a value, we have :

if (string.Contains("Value1"))    
{    
}    

How can we make the string compare with more values in an if statement without keep writing the whole statement? For example to avoid the below statement

if ((string.Contains("Value1") && (string.Contains("Value2")) && (string.Contains("Value3")))    
{    
}

Thank you

like image 467
user1805445 Avatar asked Nov 08 '12 07:11

user1805445


Video Answer


1 Answers

So, basically, you want to check if all of your values are contained in the string . Fortunately (with the help of LINQ), this can by translated almost literally into C#:

var values = new String[] {"Value1", "Value2", "Value3"};

if (values.All(v => myString.Contains(v))) {
    ...
}

Similarly, if you want to check if any value is contained in the string, you'd substitute All by Any.

like image 120
Heinzi Avatar answered Oct 14 '22 12:10

Heinzi