Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you test for a range of values in an IF statement

Tags:

c#

I'd like to test a variable ("userChoice") for the numeric values 0-32 and 99

like image 664
dhalberg Avatar asked Nov 15 '09 03:11

dhalberg


People also ask

How do you create a range condition in Excel?

To enter a range to use as a criterion, type *, enter the range reference normally, then after the range reference but before the right parenthesis, type =", then the value to match, then ".

Can an if statement have multiple conditions?

The multiple IF conditions in Excel are IF statements contained within another IF statement. They are used to test multiple conditions simultaneously and return distinct values. The additional IF statements can be included in the “value if true” and “value if false” arguments of a standard IF formula.


2 Answers

if((userChoice >= 0 && userChoice <= 32) || userChoice == 99)
{
     // do stuff
}
like image 125
Omar Avatar answered Nov 03 '22 22:11

Omar


Just to add a different kind of thinking, when I have range tests I like to use the Contains method of List<T>. In your case it may seem contrived but it would look something like:

        List<int> options = new List<int>(Enumerable.Range(0, 33));
        options.Add(99);
        if(options.Contains(userChoice)){
            // something interesting
        }

If you were operating in the simple range, it would look much cleaner:

        if(Enumerable.Range(0, 33).Contains(userChoice)){
            // something interesting
        }

What's nice about this is that is works superbly well with testing a range of strings and other types without having to write || over and over again.

like image 40
t3rse Avatar answered Nov 03 '22 22:11

t3rse