String, c# how to compare string a same time

142 Views Asked by At

Thank you in advance for your precious help. Here is my problem, I would like to compare the first two characters of MirePrincipale (which is a string) to the following character strings either "MS" or "VI" or "PF". I can only do it with only one string "MS" not the rest . Here is my code !!

if ( MirePrincipal.Substring(0, 2) == "MS" || "VI" || "PF")
    return this.MireSecondaire + " " + "(" + MirePrincipal + ")";
else
    return "Mire Principale is note a MS VI OR PF";
3

There are 3 best solutions below

0
SᴇM On BEST ANSWER

You can, for example, create an array then check if it contains what you search for:

if(new[] { "MS", "VI", "PS" }.Contains(MirePrincipal.Substring(0, 2)))
0
T.J. Crowder On

That's not how || works. Using an if, you'll have to repeat MirePrincipal.Substring(0, 2) for each == test.

You can avoid that using switch instead:

switch (MirePrincipal.Substring(0, 2)) {
    case "MS":
    case "VI":
    case "PF":
        return this.MireSecondaire + " " + "(" + MirePrincipal + ")";
    default:
        return "Mire Principale is not a MS VI OR PF";
        // No 'e' here −−−−−−−−−−−−−−−^
}

Side note: I recommend being consistent with using this. If MirePrincipal is a property (not a local variable) like MireSecondaire is, either consistently use this. with them (my recommendation) or consistently don't use this. with them, don't mix and match. (If MirePrincipal is a local variable, normal naming guidelines would say it shouldn't start with a capital M, so it should be mirePrincipal.)

2
MindSwipe On

This is a common beginner mistake (which I also made).

Basically, your if statement reads correctly in natural english (or whatever language), but it is incorrect. See it reads as "if (the first two characters of MirePrincipal equal "MS" or "VI" or "PF") then...", but that's not correct. You need to tell the computer "if (the first two characters of MirePrincipal equal "MS" or the first two characters of MirePrincipal equal "VI" ..."

So you'd need to do it like this:

if (MirePrincipal.Substring(0, 2) == "MS" || MirePrincipal.Substring(0, 2) == "VI" ||
    MirePrincipal.Substring(0, 2) == "PF")
{
    return this.MireSecondaire + " " + "(" + MirePrincipal + ")";
}

Or, as SᴇM pointed out, you could use LINQ and do it his way, but for a new programmer (which you look like you are [no worries, we were all new at some point]) I'd recommend the verbose if statement way