Home > OS >  Avoid too much if statements
Avoid too much if statements

Time:10-10

my code is something like this:

if (Enumerable.Range(1, 10).Contains(number) { return 56 }

else if (Enumerable.Range(11, 24).Contains(number) { return 55 }

Other else if statements

And this stataments till returning 35!!! How to improve this? I tried using a for loop but without success

CodePudding user response:

You could create a list of tuples containing the bounds and replacement value:

private int GetValueFromRange(int input)
{
    var ranges = new 
    {
        (LowerBound: 1, UpperBound: 10, Value: 56),
        (11, 20, 55),
        (21, 30, 54),
        // ...
    };

    foreach (var range in ranges)
    {
        if (range.LowerBound <= input && range.UpperBound >= input)
        {
            return range.Value;
        }
    }
    
    return -1;
}

But this isn't really more readable code or anything, and needs error handling added. If the range is continuous you could omit the lower bound.

CodePudding user response:

You could shorten it a little bit:

if (number < 1) throw ArgumentOutOfRangeException(nameof(number));

if (number < 11) return 56;
if (number < 25) return 55;
if (number < ??) return ??;

... and so on.

For around a dozen numbers, my personal subjective opinion is that it's more readable than defined ranges and a loop. Obviously, if you get your ranges from another source and they aren't hardcoded, that would not be possible.

CodePudding user response:

You can do a collection with limits and the expected output and then just find the correct tuple in that collection.

var limits = new List<(int, int, int)> {
    (11, 20, 1),  //lower limit, upper limit, return value
    (21, 30, 2),
    (31, 40, 3)
};
    
var number = 23;
var l = limits.FirstOrDefault(x => x.Item1 <= number && x.Item2 >= number);
    
Console.WriteLine(l.Item3);

If no valid range is found, the default return value will be 0

  •  Tags:  
  • c#
  • Related