Question

I have 5 different OR conditions in a If loop:

if(cond1 || cond2 || .... || cond5)

All conditions are bool type in C#

The problem is I have to execute certain code if any one condition is true, another code when any two conditions are true, another code when any three are true, another code when any four are true, another code when all are true and another code when none is true.

How do I solve the problem?

My approach is:

if(1 == (Convert.ToInt(cond1) + Convert.ToInt(cond2) + ... + Convert.ToInt(cond5)))
{
  //Code1
}
else if(2 == (Convert.ToInt(cond1) + Convert.ToInt(cond2) + ... + Convert.ToInt(cond5)))
{
  //Code2
}
.... and so on...

Is there any better approach?

Was it helpful?

Solution

int count =     
Convert.ToInt32(cond1)+Convert.ToInt32(cond1)+...+Convert.ToInt32(cond1);

switch(count)
{
    case 1:
    //your code here
    break;
    .
    .
    .
    case 5:
    //your code here
    break;
}

This might help you..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top