David A. David A. - 3 months ago 7
C# Question

Do action only if all loops return True

Is there a way to only trigger an action when all for loops return true?

Example:

if ((i % 1 == 0) && (i % 2 == 0) && (...) && (i % 20 == 0))
{
do action x
}


This is what I tried but it doesn´t work as expected

for(int b=1;b<21;b++)
{
if (i % b == 0)
{
// do something
}
}

Answer

Try this:

var flag = true;
for(int b = 1; b < 21; b++)
     if (i % b != 0)
     {
         flag = false;
         break;
     }
if(flag)
   SomeAction():
Comments