5

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

0

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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) {
    ...
}

1 Comment

Why would you want to keep looking after you'd already found one that didn't match?
1

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.
}

Comments

1
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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.