EDIT: New Answer provided.
I was just starting out using C# when I wrote the first answer to this question, and in hindsight I now realize that my "solution" was / is naive and inefficient.
My original answer:
I'd go with the more simple version:
`if(Enumerable.Range(1,100).Contains(intInQuestion)) { ...DoStuff; }`
A Better Way
As I haven't seen any other solution that is more efficient (according to my tests at least), I'll give it another go.
New and better way that also works with negative ranges:
// Returns true if x is in range [min..max], else false
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);
This can be used with both positive and negative ranges and defaults to a range of
1..100 (inclusive) and uses x
as the number to check followed by an optional range defined by min
and max
.
Adding Examples For Good Measure
Example 1:
// Returns true if x is in range [min..max], else false
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);
Console.WriteLine(inRange(25));
Console.WriteLine(inRange(1));
Console.WriteLine(inRange(100));
Console.WriteLine(inRange(25, 30, 150));
Console.WriteLine(inRange(-25, -50, 0));
Returns:
True
True
True
False
True
Example 2:
Using a list of 100000 random ints between 1 and 150
// Returns true if x is in range [min..max], else false
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);
// Generate 100000 ints between 1 and 150
var intsToCheck = new List<int>();
var randGen = new Random();
for(int i = 0; i < 100000; ++i){
intsToCheck.Add(randGen.Next(150) + 1);
}
var counter = 0;
foreach(int n in intsToCheck) {
if(inRange(n)) ++counter;
}
Console.WriteLine("{0} ints found in range 1..100", counter);
Returns:
66660 ints found in range 1..100
Execution Time: 0.016 second(s)