[英]Reduce the if-statement itself
This is my if-statement at the moment: 这是我目前的if语句:
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?
我应该在for循环中构建这个if语句吗?
BTW, this if-statement if already in a forloop and it uses the i of the forloop 顺便说一下,这个if语句如果已经在forloop中并且它使用了forloop的i
You can use All
: 你可以使用
All
:
if(Enumerable.Range(0, 9).All(c => excel_getValue("A" + (i + c)) == "")) {
}
There's an easy way to "reduce" (at least "beautify") with a for
loop... this wouldn't be more performant though, so you choose: 有一个简单的方法来“减少”(至少“美化”)与
for
循环...虽然这不会更高效,所以你选择:
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: 或者使用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 :-)
在性能方面没有什么比原来的更好:-)
Yes, a for
loop is a good way to simplify your code in this case. 是的,在这种情况下,
for
循环是简化代码的好方法。 Something like: 就像是:
bool result = true;
for(int j = 0; j < max; j++)
{
result = result && excel_getValue("A" + (i + j)) == "";
}
你可以尝试这样的事情:
if (Enumerable.Range(0, 8).All(p => excel_getValue("A" + (i + p)) == ""))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.