Determine if a number falls within a specified set of ranges

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

    class Range { 
    
        public Range(int x, int y) {
            X = x;
            Y = y;
        }
    
        public int X { get; set; }
        public int Y { get; set; }
    }
    
    var ranges = new List();
    ranges.Add(new Range(4199,6800));
    ranges.Add(new Range(6999,8200));
    ranges.Add(new Range(9999,10100));
    ranges.Add(new Range(10999,11100));
    ranges.Add(new Range(11999,12100));
    
    bool inRange = ranges.Count(r => x >= r.X && x <= r.Y) > 0;
    //or -- Based on Jons recommendation
    bool inRange = ranges.Any(r => x >= r.X && x <= r.Y);
    

提交回复
热议问题