Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce the if-statement itself

This is my if-statement at the moment:

   if (excel_getValue("A" + i) == "" && 
    excel_getValue("A" + (i + 1)) == "" && 
    excel_getValue("A" + (i + 2)) == "" && 
    excel_getValue("A" + (i + 3)) == "" && 
    excel_getValue("A" + (i + 4)) == "" && 
    excel_getValue("A" + (i + 5)) == "" && 
    excel_getValue("A" + (i + 6)) == "" && 
    excel_getValue("A" + (i + 7)) == "" && 
    excel_getValue("A" + (i + 8)) == "")

Is there anyway I can reduce this statement? Should I build this if-statement in a for-loop?

BTW, this if-statement if already in a forloop and it uses the i of the forloop

like image 319
wouter Avatar asked Jun 10 '15 08:06

wouter


People also ask

Can you have an if statement by itself?

It is only bad if you need to do something when the condition is false. No, absolutely not! In fact, it is very common to have an if without an else when there is no specific activity that needs to be performed when the condition is false.

How do you reduce IF statements in Python?

Use If/Else Statements in One Line To simplify the code and reduce the number of lines in the conditional statements, you can use an inline if conditional statement. Consider the following concise code that performs the same with one line for each if/else conditional statement.

Should you avoid if statements?

There is nothing wrong with using if-statements, but avoiding them can sometimes make the code a bit more readable to humans. This is definitely not a general rule as sometimes avoiding if-statements will make the code a lot less readable. You be the judge. Avoiding if-statements is not just about readability.


2 Answers

You can use All:

if(Enumerable.Range(0, 9).All(c => excel_getValue("A" + (i + c)) == "")) {
}
like image 57
Lee Avatar answered Oct 15 '22 00:10

Lee


There's an easy way to "reduce" (at least "beautify") with a for loop... this wouldn't be more performant though, so you choose:

bool do = true;
for(var j = 0; j < 9; j++) { 
   if (excel_getValue("A" + (i+j)) != "") {
     do = false;
     break;
   }
}
if(do) { /* whatever */ }

Or using Linq:

if(Enumerable.Range(0, 9).All(x => excel_getValue("A" + (i + x)) == "")) { /* whatever */ }

This could be probably reduced easily, but I guess the point is that it should be "prettier", and not "better" or "complicated". Nothing would beat your original one in terms of performance :-)

like image 34
Jcl Avatar answered Oct 14 '22 23:10

Jcl