Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write like "x == either 1 or 2" in a programming language? [duplicate]

Possible Duplicate:
Why do most programming languages only have binary equality comparison operators?

I have had a simple question for a fairly long time--since I started learning programming languages.

I'd like to write like "if x is either 1 or 2 => TRUE (otherwise FALSE)."

But when I write it in a programming language, say in C,

( x == 1 || x == 2 )

it really works but looks awkward and hard to read. I guess it should be possible to simplify such an or operation, and so if you have any idea, please tell me. Thanks, Nathan

like image 537
Culip Avatar asked Sep 11 '25 01:09

Culip


2 Answers

Python allows test for membership in a sequence:

if x in (1, 2):
like image 76
Ignacio Vazquez-Abrams Avatar answered Sep 13 '25 07:09

Ignacio Vazquez-Abrams


An extension version in C#

step 1: create an extension method

public static class ObjectExtensions
{
    public static bool Either(this object value, params object[] array)
    {
        return array.Any(p => Equals(value, p));
    }
}

step 2: use the extension method

if (x.Either(1,2,3,4,5,6)) 
{
}
else
{
}
like image 36
Andre Haverdings Avatar answered Sep 13 '25 07:09

Andre Haverdings