views:

319

answers:

8

How can I check if a condition passes multiple values

Example:

if(number == 1,2,3)

I know that commas don't work.

EDIT: Thanks!

+1  A: 
if ((number >= 1) && (number <= 3))
Bombe
Assumes the values will always be in order.
csl
+1  A: 

What language?

For example in VB.NET you use the word OR, and in C# you use ||

Brandon
+2  A: 
if (number == 1 || number == 2 || number == 3)
fretje
thanks, umm additional characters needed.
Phil
A: 

In T-SQL you can use the IN operator:

select * from MyTable where ID in (1,2,3)

If you are using a collection there may be a contains operator for another way to do this.

In C# for another way that may be easier to add values:

    List<int> numbers = new List<int>(){1,2,3};
    if (numbers.Contains(number))
JB King
A: 

Since you specify no language I add a Python solution:

if number in [1, 2, 3]:
    pass
Joachim Sauer
A: 

Haha! Wow! Thanks guys,

I tried (number == 1),(number == 2)

and (number 1 || 2 || 3)

Thanks again for the quick response...

Phil
A: 

I'll assume a C-Style language, here's a quick primer on IF AND OR logic:

if(variable == value){
    //does something if variable is equal to value
}

if(!variable == value){
    //does something if variable is NOT equal to value
}

if(variable1 == value1 && variable2 == value2){
    //does something if variable1 is equal to value1 AND variable2 is equal to value2
}

if(variable1 == value1 || variable2 = value2){
    //does something if variable1 is equal to value1 OR  variable2 is equal to value2
}

if((variable1 == value1 && variable2 = value2) || variable3 == value3){
    //does something if:
    // variable1 is equal to value1 AND variable2 is equal to value2
    // OR variable3 equals value3 (regardless of variable1 and variable2 values)
}

if(!(variable1 == value1 && variable2 = value2) || variable3 == value3){
    //does something if:
    // variable1 is NOT equal to value1 AND variable2 is NOT equal to value2
    // OR variable3 equals value3 (regardless of variable1 and variable2 values)
}

So you can see how you can chain these checks together to create some pretty complex logic.

JStriedl
A: 

For a list of integers:

static bool Found(List<int> arr, int val)
    {
        int result = default(int);
        if (result == val)
            result++;

        result = arr.FindIndex(delegate(int myVal)
        {
            return (myVal == val);
        });
        return (result > -1);
    }
Thomasek