猿问

检查数字是否在范围内的最快方法

检查一个数字是否在一个范围内的最简单方法是什么,除了


if (Enumerable.Range(1,100).Contains(number))

//true


if (x >= 1 && x <= 100)

//true

这些方式?也许更有效的东西?


慕森王
浏览 135回答 2
2回答

青春有我

没有什么比第二种选择更有效的了。你可以写一个扩展:public static class NumberExtensions{&nbsp; &nbsp; public static bool IsWithinRange<T>(this T number, T rangeStart, T rangeEnd) where T : IComparable<T>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return number.CompareTo(rangeStart) >= 0 && number.CompareTo(rangeEnd) <= 0;&nbsp; &nbsp; }}现在代码可读且高效:if (x.IsWithinRange(1, 100)){}

Cats萌萌

第一个(LINQ)选项非常低效。第二个选项(只需检查不等式运算符)就可以了。在有多个范围的一般情况下,您可以使用新的switch改进:&nbsp; &nbsp; switch(number)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; case var n when n >= 1 && n <= 100:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case var n when n > 100:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答