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

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

    In production code I would simply write

    1 <= x && x <= 100
    

    This is easy to understand and very readable.

    Starting with C#9.0 we can write

    x is >= 1 and <= 100   // Note that we have to write x only once.
                           // "is" introduces a pattern matching expression.
                           // "and" is part of the pattern matching unlike the logical "&&".
                           // With "&&" we would have to write: x is >= 1 && x is <= 100
    

    Here is a clever method that reduces the number of comparisons from two to one by using some math. The idea is that one of the two factors becomes negative if the number lies outside of the range and zero if the number is equal to one of the bounds:

    If the bounds are inclusive:

    (x - 1) * (100 - x) >= 0
    

    or

    (x - min) * (max - x) >= 0
    

    If the bounds are exclusive:

    (x - 1) * (100 - x) > 0
    

    or

    (x - min) * (max - x) > 0
    

提交回复
热议问题