Andrew
Andrew

Reputation: 2539

Combining multiple conditional expressions in C#

In C#, instead of doing if(index == 7 || index == 8), is there a way to combine them? I'm thinking of something like if(index == (7, 8)).

Upvotes: 23

Views: 4929

Answers (9)

Paul Sasik
Paul Sasik

Reputation: 81459

You could put the values that you need to compare into an inline array and use a Contains extension method. See this article for starters.

Several snippets demonstrating the concept:

int index = 1;
Console.WriteLine("Example 1: ", new int[] { 1, 2, 4 }.Contains(index));

index = 2;
Console.WriteLine("Example 2: ", new int[] { 0, 5, 3, 4, 236 }.Contains(index));

Output:

Example 1: True
Example 2: False

Upvotes: 9

Jeff Hubbard
Jeff Hubbard

Reputation: 9892

There is no way, in the current C# syntax set, to combine multiple right-hand-side operands to be passed to a single binary operator to the best of my knowledge.

Upvotes: 3

AMH
AMH

Reputation: 6451

Do u need something like that

        int x = 5; 

        if((new int[]{5,6}).Contains(x)) 
        {
            Console.WriteLine("true");


        }
        Console.ReadLine();

Upvotes: 0

agent-j
agent-j

Reputation: 27913

switch (GetExpensiveValue())
{
case 7: case 8:
   // do work
   break;
}

This obviously takes more code, but it may save you from evaluating a function a bunch of times.

Upvotes: 2

Coeffect
Coeffect

Reputation: 8866

No way to do that, but you could certainly do a range using if( index >=7 && index <= 8 ). But giving it a list of numbers would require you to create an array or list object and then use a method to do this. But that's just overkill.

Upvotes: 0

48klocs
48klocs

Reputation: 6103

You can accomplish this with an extension method.

public static bool In<T>(this T obj, params T[] collection) {
   return collection.Contains(obj);
}

Then...

if(index.In(7,8))
{
    ...
}

Upvotes: 55

SQLMason
SQLMason

Reputation: 3275

if ((new int[]{7,8}).Contains(index))

Upvotes: 1

Ed Bayiates
Ed Bayiates

Reputation: 11210

You could use this:

 if (new List<int>() { 7, 8 }.Contains(index))

Upvotes: 2

Tundey
Tundey

Reputation: 2965

Write your own extension methods so you can write

if (index.Between(7, 8)) {...}

where Between is defined as:

    public static bool Between (this int a, int x, int y)
    {
        return a >= x && a <= y;
    }

Upvotes: 2

Related Questions