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

后端 未结 27 2112
挽巷
挽巷 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

    I was looking for an elegant way to do it where the bounds might be switched (ie. not sure which order the values are in).

    This will only work on newer versions of C# where the ?: exists

    bool ValueWithinBounds(float val, float bounds1, float bounds2)
    {
        return bounds1 >= bounds2 ?
          val <= bounds1 && val >= bounds2 : 
          val <= bounds2 && val >= bounds1;
    }
    

    Obviously you could change the = signs in there for your purposes. Could get fancy with type casting too. I just needed a float return within bounds (or equal to)

提交回复
热议问题