Determine if a number falls within a specified set of ranges

后端 未结 8 1445
耶瑟儿~
耶瑟儿~ 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:11

    Try something like:

    struct Range
    {
       public readonly int LowerBound;
       public readonly int UpperBound; 
    
       public Range( int lower, int upper )
       { LowerBound = lower; UpperBound = upper; }
    
       public bool IsBetween( int value )
       { return value >= LowerBound && value <= UpperBound; }
    }
    
    public void YourMethod( int someValue )
    {
       List<Range> ranges = {new Range(4199,6800),new Range(6999,8200),
                             new Range(9999,10100),new Range(10999,11100),
                             new Range(11999,12100)};
    
       if( ranges.Any( x => x.IsBetween( someValue ) )
       {
          // your awesome code...
       }
    }
    
    0 讨论(0)
  • 2021-02-02 14:14

    I personally prefer the extension method suggested by @Anton - but if you can't do that, and are going to stick with your current code, I think you could make it more readable by reversing the first set of conditions on each line as follows...

    int x = 500; // Could be any number
    if ( ( 4199 < x && x < 6800 ) ||
         ( 6999 < x && x < 8200 ) ||
         ( 9999 < x && x < 10100 ) ||
         ( 10999 < x && x < 11100 ) ||
         ( 11999 < x && x < 12100 ) )
    {
        // More awesome code
    }
    
    0 讨论(0)
提交回复
热议问题