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

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

    There are a lot of options:

    int x = 30;
    if (Enumerable.Range(1,100).Contains(x))
        //true
    
    if (x >= 1 && x <= 100)
        //true
    

    Also, check out this SO post for regex options.

提交回复
热议问题