Goran
Goran

Reputation: 6518

Find a value in a range = is there such a code keyword in c#?

In a lot of situations we have to do something like this:

if (someVariable == value1 || someVariable == value2 || someVariable == value1...)

Would it be nice if we can do this in following manner:

if (someVariable in {value1, value2, value3...}

We can do this

int[] arr = {value1, value2, value3....};
if (arr.Contains(someVariable)) ...

But its still overwhelming, to my opinion. Why there isn't a support for this syntax, or there is but I don't know about it?

Upvotes: 0

Views: 111

Answers (4)

Paul Keister
Paul Keister

Reputation: 13077

Use a HashSet for this:

var hs = new HashSet<int>();
hs.Add(1);
hs.Add(2);
...
if(hs.Contains(x))
{
   //bingo!
}

Upvotes: 7

Frank
Frank

Reputation: 3143

Use the Contains method of HashSet. I am not sure how this improves code clarity since you are still forced to check all three conditions.

Upvotes: 0

Joe
Joe

Reputation: 166

I think this may be about as concise as you may get:

if (new int[] { 1, 2, 3 }.Contains(2))
{
    Console.WriteLine("bleh");
}

Upvotes: 9

Stu
Stu

Reputation: 15769

How about

switch (someVariable)
{
    case value1:
    case value2:
    case value3:
    case value12345:
        doSomething();
        break;
    default:
        doSomethingElse();
        break;
}

Upvotes: 2

Related Questions