-1

I wanted an if-else clause to behave based on an input that would leave the statements as is, or switch statements between if and else.

To be specific, I am parsing an html tag country and uncountry. Based on its attribute, which lists the countries for the tag, I will be able to decide whether to skip the inner content or not. country tag will copy inner content, while uncountry does the opposite. The if (parseCountry) is to parse country tag, and the else for uncountry tag.

For example:

                if (parseCountry)
                {
                    if (inCountryList)
                    {
                        do A;
                        do B;
                    }
                    else if (notInCountryList)
                        do C;
                }
                else
                {
                    if (inCountryList)
                        do C;
                    else if (notInCountryList)
                    {
                        do A;
                        do B;
                    }
                }

What is the best way to simplify the if-else statements above? Thanks.

Anabell CC
  • 39
  • 1
  • 7

2 Answers2

1

I guess this is what you're looking for:

if (parseCountry == inCountryList)
{
    do A;
    do B;
}
else
{
    do C;
}

The condition is fulfilled when both booleans have the same value: either both are True or both are False.

Kapol
  • 6,383
  • 3
  • 21
  • 46
  • This answer would be a good one if you had incorporated the OP's `notInCountryList` variable as well. – Peter Duniho Nov 28 '15 at 00:28
  • Sorry, this won't do. I am parsing tags in an html string. One of those tags is a tag. And in the country tag, I need to know if my current country is in the list If my current country is in the list, I will show the inner content. If not, I will hide the inner content. – Anabell CC Dec 01 '15 at 21:35
1

For convenience, I'm going to use do AB; to reflect your two-statement block.

To summarize the logic you want to implement: if parseCountry and inCountryList both have the same value, execute do AB;, otherwise execute do C;, but with the provision that in either case, the !inCountryList case should be executed only if notInCountryList is itself true.

Written out in C#(-ish) code, that would look something like this:

if (inCountryList || notInCountryList)
{
    if (parseCountry == inCountryList)
    {
        do A;
        do B;
    }
    else
    {
        do C;
    }
}

Or put another way: if neither inCountryList or notInCountryList are true, do nothing. Otherwise, execute the code according to whether parseCountry is equal to inCountryList. This is consistent with the implementation you've shown in your question.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136