Determine if a number falls within a specified set of ranges

后端 未结 8 1460
耶瑟儿~
耶瑟儿~ 2021-02-02 13:45

I\'m looking for a fluent way of determining if a number falls within a specified set of ranges. My current code looks something like this:

int x = 500; // Could         


        
8条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 14:05

    Extension methods?

    bool Between(this int value, int left, int right)
    { 
       return value > left && value < right; 
    }
    
    if(x.Between(4199, 6800) || x.Between(6999, 8200) || ...)
    

    You can also do this awful hack:

    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, ...)
    

    Awful hack, improved:

    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), ...))
    

    Or, better yet (this does not allow duplicate lower bounds):

    bool Between(this int value, Dictionary ranges)
    {
        // Basically iterate over Key-Value pairs and check if value falls within that range
    }
    
    if(x.Between({ { 4199, 6800 }, { 6999, 8200 }, ... }
    

提交回复
热议问题