How to elegantly check if a number is within a range?

后端 未结 27 1887
挽巷
挽巷 2020-11-27 11:17

How can I do this elegantly with C# and .NET 3.5/4?

For example, a number can be between 1 and 100.

I know a simple if would suffice; but the keyword to this

相关标签:
27条回答
  • 2020-11-27 11:38

    These are some Extension methods that can help

      public static bool IsInRange<T>(this T value, T min, T max)
    where T : System.IComparable<T>
        {
            return value.IsGreaterThenOrEqualTo(min) && value.IsLessThenOrEqualTo(max);
        }
    
    
        public static bool IsLessThenOrEqualTo<T>(this T value, T other)
             where T : System.IComparable<T>
        {
            var result = value.CompareTo(other);
            return result == -1 || result == 0;
        }
    
    
        public static bool IsGreaterThenOrEqualTo<T>(this T value, T other)
             where T : System.IComparable<T>
        {
            var result = value.CompareTo(other);
            return result == 1 || result == 0;
        }
    
    0 讨论(0)
  • 2020-11-27 11:40

    Cause all the other answer are not invented by me, here just my implementation:

    public enum Range
    {
        /// <summary>
        /// A range that contains all values greater than start and less than end.
        /// </summary>
        Open,
        /// <summary>
        /// A range that contains all values greater than or equal to start and less than or equal to end.
        /// </summary>
        Closed,
        /// <summary>
        /// A range that contains all values greater than or equal to start and less than end.
        /// </summary>
        OpenClosed,
        /// <summary>
        /// A range that contains all values greater than start and less than or equal to end.
        /// </summary>
        ClosedOpen
    }
    
    public static class RangeExtensions
    {
        /// <summary>
        /// Checks if a value is within a range that contains all values greater than start and less than or equal to end.
        /// </summary>
        /// <param name="value">The value that should be checked.</param>
        /// <param name="start">The first value of the range to be checked.</param>
        /// <param name="end">The last value of the range to be checked.</param>
        /// <returns><c>True</c> if the value is greater than start and less than or equal to end, otherwise <c>false</c>.</returns>
        public static bool IsWithin<T>(this T value, T start, T end) where T : IComparable<T>
        {
            return IsWithin(value, start, end, Range.ClosedOpen);
        }
    
        /// <summary>
        /// Checks if a value is within the given range.
        /// </summary>
        /// <param name="value">The value that should be checked.</param>
        /// <param name="start">The first value of the range to be checked.</param>
        /// <param name="end">The last value of the range to be checked.</param>
        /// <param name="range">The kind of range that should be checked. Depending on the given kind of range the start end end value are either inclusive or exclusive.</param>
        /// <returns><c>True</c> if the value is within the given range, otherwise <c>false</c>.</returns>
        public static bool IsWithin<T>(this T value, T start, T end, Range range) where T : IComparable<T>
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));
    
            if (start == null)
                throw new ArgumentNullException(nameof(start));
    
            if (end == null)
                throw new ArgumentNullException(nameof(end));
    
            switch (range)
            {
                case Range.Open:
                    return value.CompareTo(start) > 0
                           && value.CompareTo(end) < 0;
                case Range.Closed:
                    return value.CompareTo(start) >= 0
                           && value.CompareTo(end) <= 0;
                case Range.OpenClosed:
                    return value.CompareTo(start) > 0
                           && value.CompareTo(end) <= 0;
                case Range.ClosedOpen:
                    return value.CompareTo(start) >= 0
                           && value.CompareTo(end) < 0;
                default:
                    throw new ArgumentException($"Unknown parameter value {range}.", nameof(range));
            }
        }
    }
    

    You can then use it like this:

    var value = 5;
    var start = 1;
    var end = 10;
    
    var result = value.IsWithin(start, end, Range.Closed);
    
    0 讨论(0)
  • 2020-11-27 11:41

    Do you mean?

    if(number >= 1 && number <= 100)
    

    or

    bool TestRange (int numberToCheck, int bottom, int top)
    {
      return (numberToCheck >= bottom && numberToCheck <= top);
    }
    
    0 讨论(0)
  • 2020-11-27 11:42

    A new twist on an old favorite:

    public bool IsWithinRange(int number, int topOfRange, int bottomOfRange, bool includeBoundaries) {
        if (includeBoundaries)
            return number <= topOfRange && number >= bottomOfRange;
        return number < topOfRange && number > bottomOfRange;
    }
    
    0 讨论(0)
  • 2020-11-27 11:45

    Just to add to the noise here, you could create an extension method:

    public static bool IsWithin(this int value, int minimum, int maximum)
    {
        return value >= minimum && value <= maximum;
    }
    

    Which would let you do something like...

    int val = 15;
    
    bool foo = val.IsWithin(5,20);
    

    That being said, this seems like a silly thing to do when the check itself is only one line.

    0 讨论(0)
  • 2020-11-27 11:45

    Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:

    public static bool IsBetween(this int value, int min, int max)
    {
        return min <= value && value <= max;
    }
    

    For further illustration:

    public static bool IsOutside(this int value, int min, int max)
    {
        return value < min || max < value;
    }
    
    0 讨论(0)
提交回复
热议问题