Home > Software engineering >  Effective/ Short way to write a condition like if(a && b) else if(a) else if(b)
Effective/ Short way to write a condition like if(a && b) else if(a) else if(b)

Time:09-19

im very sure this question was already asked somewhere, but i couldn´t phrase my question right to get proper results. Im am looking for a shorter, more effective way to write this condition

var test = new List<int>() { 1, 2 };
if (test.Contains(1) && test.Contains(2))
{
    //Do stuff
}
else if (test.Contains(1))
{
    //Do stuff
}
else if (test.Contains(2))
{
    //Do stuff
}

I only came up with this idea, wich is hard to read in my opinion

var result = test.Contains(1)
            ? test.Contains(2)
                ? "1 and 2"
                : "1"
            : "2";

(Note that this is just an example. This also applies to other cases, such as two booleans which, when both true, should execute different code than if only one of them is true.

Edit1: As pointed out, the output of my idea is not equivalent to the first code snipped. Therefore it seems to be no valid solution.

Edit2: Further information to "Do stuff": All three "Do stuff" would execute completely different code, so that it is not possible to rephrase the condition to only use if(a) and if(b).

Hope this example helps:

string result = "";
var test = new List<int>() { 1, 2 };
if (test.Contains(1) && test.Contains(2))
{
    //Do Something completely different
    TriggerAnotherProcess();
}
else if (test.Contains(1))
{
    result = "1";
}
else if (test.Contains(2))
{
    result = "2";
}

CodePudding user response:

You are checking multiple times if the list contains a number, i'd do it only once, so use a variable:

bool contains1 = test.Contains(1);
bool contains2 = test.Contains(2);

if (contains1 && contains2)
{
    //Do stuff
}
else if (contains1)
{
    //Do stuff
}
else if (contains2)
{
    //Do stuff
}

Apart from that i don't know a way to simplify it further.

Edit: with your provided real code, you could simplify it to:

bool contains1 = test.Contains(1);
bool contains2 = test.Contains(2);
string result = contains1 == contains2 ? "" : contains1 ? "1" : "2";

if (contains1 && contains2)
{
    TriggerAnotherProcess();
}

CodePudding user response:

I think that the way you're doing it is fine, otherwise you're heading towards exotic approaches like this:

var options = new Dictionary<(bool test1, bool test2), Action>()
{
    { (true, true), () => { /* Do Stuff */ } },
    { (false, true), () => { /* Do Stuff */ } },
    { (true, false), () => { /* Do Stuff */ } },
    { (false, false), () => { /* Do Stuff */ } },
};

var test = new List<int>() { 1, 2 };

options[(test.Contains(1), test.Contains(2))]();
  •  Tags:  
  • c#
  • Related