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

后端 未结 27 1891
挽巷
挽巷 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:56

    If it's to validate method parameters, none of the solutions throw ArgumentOutOfRangeException and allow easy/proper configuration of inclusive/exclusive min/max values.

    Use like this

    public void Start(int pos)
    {
        pos.CheckRange(nameof(pos), min: 0);
    
        if (pos.IsInRange(max: 100, maxInclusive: false))
        {
            // ...
        }
    }
    

    I just wrote these beautiful functions. It also has the advantage of having no branching (a single if) for valid values. The hardest part is to craft the proper exception messages.

    /// <summary>
    /// Returns whether specified value is in valid range.
    /// </summary>
    /// <typeparam name="T">The type of data to validate.</typeparam>
    /// <param name="value">The value to validate.</param>
    /// <param name="min">The minimum valid value.</param>
    /// <param name="minInclusive">Whether the minimum value is valid.</param>
    /// <param name="max">The maximum valid value.</param>
    /// <param name="maxInclusive">Whether the maximum value is valid.</param>
    /// <returns>Whether the value is within range.</returns>
    public static bool IsInRange<T>(this T value, T? min = null, bool minInclusive = true, T? max = null, bool maxInclusive = true)
        where T : struct, IComparable<T>
    {
        var minValid = min == null || (minInclusive && value.CompareTo(min.Value) >= 0) || (!minInclusive && value.CompareTo(min.Value) > 0);
        var maxValid = max == null || (maxInclusive && value.CompareTo(max.Value) <= 0) || (!maxInclusive && value.CompareTo(max.Value) < 0);
        return minValid && maxValid;
    }
    
    /// <summary>
    /// Validates whether specified value is in valid range, and throws an exception if out of range.
    /// </summary>
    /// <typeparam name="T">The type of data to validate.</typeparam>
    /// <param name="value">The value to validate.</param>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="min">The minimum valid value.</param>
    /// <param name="minInclusive">Whether the minimum value is valid.</param>
    /// <param name="max">The maximum valid value.</param>
    /// <param name="maxInclusive">Whether the maximum value is valid.</param>
    /// <returns>The value if valid.</returns>
    public static T CheckRange<T>(this T value, string name, T? min = null, bool minInclusive = true, T? max = null, bool maxInclusive = true)
    where T : struct, IComparable<T>
    {
        if (!value.IsInRange(min, minInclusive, max, maxInclusive))
        {
            if (min.HasValue && minInclusive && max.HasValue && maxInclusive)
            {
                var message = "{0} must be between {1} and {2}.";
                throw new ArgumentOutOfRangeException(name, value, message.FormatInvariant(name, min, max));
            }
            else
            {
                var messageMin = min.HasValue ? GetOpText(true, minInclusive).FormatInvariant(min) : null;
                var messageMax = max.HasValue ? GetOpText(false, maxInclusive).FormatInvariant(max) : null;
                var message = (messageMin != null && messageMax != null) ?
                    "{0} must be {1} and {2}." :
                    "{0} must be {1}.";
                throw new ArgumentOutOfRangeException(name, value, message.FormatInvariant(name, messageMin ?? messageMax, messageMax));
            }
        }
        return value;
    }
    
    private static string GetOpText(bool greaterThan, bool inclusive)
    {
        return (greaterThan && inclusive) ? "greater than or equal to {0}" :
            greaterThan ? "greater than {0}" :
            inclusive ? "less than or equal to {0}" :
            "less than {0}";
    }
    
    public static string FormatInvariant(this string format, params object?[] args) => string.Format(CultureInfo.InvariantCulture, format, args);
    
    0 讨论(0)
  • 2020-11-27 11:57

    If you want to write more code than a simple if, maybe you can: Create a Extension Method called IsBetween

    public static class NumberExtensionMethods
    {
        public static bool IsBetween(this long value, long Min, long Max)
        {
            // return (value >= Min && value <= Max);
            if (value >= Min && value <= Max) return true;
            else return false;
        }
    }
    

    ...

    // Checks if this number is between 1 and 100.
    long MyNumber = 99;
    MessageBox.Show(MyNumber.IsBetween(1, 100).ToString());
    

    Addendum: it's worth noting that in practice you very rarely "just check for equality" (or <, >) in a codebase. (Other than in the most trivial situations.) Purely as an example, any game programmer would use categories something like the following in every project, as a basic matter. Note that in this example it (happens to be) using a function (Mathf.Approximately) which is built in to that environment; in practice you typically have to carefully develop your own concepts of what comparisons means for computer representations of real numbers, for the type of situation you are engineering. (Don't even mention that if you're doing something like, perhaps a controller, a PID controller or the like, the whole issue becomes central and very difficult, it becomes the nature of the project.) BY no means is the OP question here a trivial or unimportant question.

    private bool FloatLessThan(float a, float b)
        {
        if ( Mathf.Approximately(a,b) ) return false;
        if (a<b) return true;
        return false;
        }
    
    private bool FloatLessThanZero(float a)
        {
        if ( Mathf.Approximately(a,0f) ) return false;
        if (a<0f) return true;
        return false;
        }
    
    private bool FloatLessThanOrEqualToZero(float a)
        {
        if ( Mathf.Approximately(a,0f) ) return true;
        if (a<0f) return true;
        return false;
        }
    
    0 讨论(0)
  • 2020-11-27 11:59

    As others said, use a simple if.

    You should think about the ordering.

    e.g

    1 <= x && x <= 100
    

    is easier to read than

    x >= 1 && x <= 100
    
    0 讨论(0)
  • 2020-11-27 11:59

    In C, if time efficiency is crucial and integer overflows will wrap, one could do if ((unsigned)(value-min) <= (max-min)) .... If 'max' and 'min' are independent variables, the extra subtraction for (max-min) will waste time, but if that expression can be precomputed at compile time, or if it can be computed once at run-time to test many numbers against the same range, the above expression may be computed efficiently even in the case where the value is within range (if a large fraction of values will be below the valid range, it may be faster to use if ((value >= min) && (value <= max)) ... because it will exit early if value is less than min).

    Before using an implementation like that, though, benchmark one one's target machine. On some processors, the two-part expression may be faster in all cases since the two comparisons may be done independently whereas in the subtract-and-compare method the subtraction has to complete before the compare can execute.

    0 讨论(0)
  • 2020-11-27 12:01

    You are looking for in [1..100]? That's only Pascal.

    0 讨论(0)
  • 2020-11-27 12:02
    static class ExtensionMethods
    {
        internal static bool IsBetween(this double number,double bound1, double bound2)
        {
            return Math.Min(bound1, bound2) <= number && number <= Math.Max(bound2, bound1);
        }
    
        internal static bool IsBetween(this int number, double bound1, double bound2)
        {
            return Math.Min(bound1, bound2) <= number && number <= Math.Max(bound2, bound1);
        }
    }
    

    Usage

    double numberToBeChecked = 7;

    var result = numberToBeChecked.IsBetween(100,122);

    var result = 5.IsBetween(100,120);

    var result = 8.0.IsBetween(1.2,9.6);

    0 讨论(0)
提交回复
热议问题