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

后端 未结 27 2125
挽巷
挽巷 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 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);

提交回复
热议问题