Reputation: 33
What is the easiest way of checking if a number is within a range, besides
if (Enumerable.Range(1,100).Contains(number))
//true
if (x >= 1 && x <= 100)
//true
these ways? Something perhaps more effective?
Upvotes: 0
Views: 1610
Reputation: 1062640
The first (LINQ) option is horribly inefficient. The second option (just check with inequality operators) is fine. In the general case when you have multiple ranges, you can use the new switch
improvements:
switch(number)
{
case var n when n >= 1 && n <= 100:
// ...
break;
case var n when n > 100:
// ...
break;
default:
// ...
break;
}
Upvotes: 2
Reputation: 460068
There's nothing more efficient than the second option. You could write an extension:
public static class NumberExtensions
{
public static bool IsWithinRange<T>(this T number, T rangeStart, T rangeEnd) where T : IComparable<T>
{
return number.CompareTo(rangeStart) >= 0 && number.CompareTo(rangeEnd) <= 0;
}
}
Now the code is readable and efficient:
if (x.IsWithinRange(1, 100))
{
}
Upvotes: 7