开发者

Is there an elegant way to replace if by something like switch when dealing with intervals?

Is there a way in .NET to replace a code where intervals are compared like

if (compare < 10)
  开发者_StackOverflow社区      {
            // Do one thing
        }
        else if (10 <= compare && compare < 20)
        {
            // Do another thing
        }
        else if (20 <= compare && compare < 30)
        {
            // Do yet another thing
        }
        else
        {
            // Do nothing
        }

by something more elegant like a switch statement (I think in Javascript "case (<10)" works, but in c#)? Does anyone else find this code is ugly as well?


One simplification: since these are all else-if instead of just if, you don't need to check the negation of the previous conditions. I.e., this is equivalent to your code:

if (compare < 10)
{
    // Do one thing
}
else if (compare < 20)
{
    // Do another thing
}
else if (compare < 30)
{
    // Do yet another thing
}
else
{
    // Do nothing
}


Since you've already affirmed that compare >= 10 after the first if, you really don't need the lower bound test on the second (or any of the other) ifs...

It's not pretty, but switch was originally implemented by hashing in C, so that it was actually faster than an if...else if chain. Such an implementation doesn't translate well to general ranges, and that's also why only constant cases were allowed.

However, for the example you give you could actually do something like:

switch(compare/10) {
    case 0:
        // Do one thing
    break;
    case 1:
        // Do another thing
    break;
    case 2:
        // Do yet another thing
    break;
    default;
        // Do nothing
    break;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜