确定数字是否在指定范围内

确定数字是否在指定范围内

我正在寻找一种确定数字是否在指定范围内的流利方法。我当前的代码如下所示:

int x = 500; // Could be any number

if ( ( x > 4199 && x < 6800 ) ||
     ( x > 6999 && x < 8200 ) ||
     ( x > 9999 && x < 10100 ) ||
     ( x > 10999 && x < 11100 ) ||
     ( x > 11999 && x < 12100 ) )
{
    // More awesome code
}

有更好的方法吗?

最佳答案

扩展方法?

bool Between(this int value, int left, int right)
{
   return value > left && value < right;
}

if(x.Between(4199, 6800) || x.Between(6999, 8200) || ...)

您也可以这样做:
bool Between(this int value, params int[] values)
{
    // Should be even number of items
    Debug.Assert(values.Length % 2 == 0);

    for(int i = 0; i < values.Length; i += 2)
        if(!value.Between(values[i], values[i + 1])
            return false;

    return true;
}

if(x.Between(4199, 6800, 6999, 8200, ...)

骇人的骇客,已改进:
class Range
{
    int Left { get; set; }
    int Right { get; set; }

    // Constructors, etc.
}

Range R(int left, int right)
{
    return new Range(left, right)
}

bool Between(this int value, params Range[] ranges)
{
    for(int i = 0; i < ranges.Length; ++i)
        if(value > ranges[i].Left && value < ranges[i].Right)
            return true;

    return false;
}

if(x.Between(R(4199, 6800), R(6999, 8200), ...))

或者,更好的是(这不允许重复的下界):
bool Between(this int value, Dictionary<int, int> ranges)
{
    // Basically iterate over Key-Value pairs and check if value falls within that range
}

if(x.Between({ { 4199, 6800 }, { 6999, 8200 }, ... }

关于c# - 确定数字是否在指定范围内,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1137499/

10-10 15:35