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

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

    If you are concerned with the comment by @Daap on the accepted answer and can only pass the value once, you could try one of the following

    bool TestRangeDistance (int numberToCheck, int bottom, int distance)
    {
      return (numberToCheck >= bottom && numberToCheck <= bottom+distance);
    }
    
    //var t = TestRangeDistance(10, somelist.Count()-5, 10);
    

    or

    bool TestRangeMargin (int numberToCheck, int target, int margin)
    {
      return (numberToCheck >= target-margin && numberToCheck <= target+margin);
    }
    
    //var t = TestRangeMargin(10, somelist.Count(), 5);
    

提交回复
热议问题