Is there an elegant way to replace if something like switching when working at intervals?

Is there a way in .NET to replace code where intervals are compared, for example

if (compare < 10)
        {
            // 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
        }

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

+5
source share
2 answers

One simplification: since this is all the rest - if instead of being simple, you do not need to check the negation of the previous conditions. Ie, 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
}
+4
source

, compare >= 10 if, ( ) if s...

, switch C, , if...else if. , .

, , - :

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;
}
+2

All Articles