user1805445
user1805445

Reputation: 159

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

Upvotes: 5

Views: 5305

Answers (5)

Talha
Talha

Reputation: 19262

if(stringArray.Any(s => stringToCheck.Contains(s)))

If you want to ensure that it contains all the substrings, change Any to All:

if(stringArray.All(s => stringToCheck.Contains(s)))

Upvotes: 1

Captain Kenpachi
Captain Kenpachi

Reputation: 7215

Is this the best solution? Probably not. Is it readable and extendable? Yes.

var matches = {"string1", "string2", "string3","string-n"};
var i = 0;
foreach(string s in matches)
{
    if(mystring.Contains(s))
    {
        i++;
    }
}
if(i == matches.Length)
{
    //string contains all matches.
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500815

Well, you could use LINQ:

string[] requiredContents = { "Foo", "Bar", "Baz" };

if (requiredContents.All(x => text.Contains(x))
{
    ...
}

Note that just like the short-circuiting && operator, All will stop as soon as it finds a value which doesn't satisfy the condition. (If you want to use Any in a similar way elsewhere, that will stop as soon as it finds a value which does satisfy the condition.)

I wouldn't bother for only a reasonably small number though. Without the extraneous brackets, it's really not that bad:

if (text.Contains("foo") && text.Contains("bar") && text.Contains("Baz"))
{
}

I would only start using the more general form if either there were genuinely quite a few values (I'd probably draw the line at about 5) or if the set of values was being passed in as a parameter, or varied in some other way.

Upvotes: 3

Francois
Francois

Reputation: 10978

As you need "your" string to contains all values:

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

if (values.Count(v => s.Contains(v)) == values.Length) {
    ...
}

Upvotes: 1

Heinzi
Heinzi

Reputation: 172280

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.

Upvotes: 7

Related Questions