Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)).

like image 282
Andrew Avatar asked Jun 17 '11 18:06

Andrew


People also ask

Can you put multiple conditions in an if statement in C?

nested-if in C/C++ Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.

How do you combine conditional statements?

The & ( and ) and the | ( or ) operators are used to combine conditional statements in R . Conditional statements in R programming are used to make decisions based on certain conditions. In a simpler term, a conditional statement is a type of coding instruction used to compare values and expressions to make decisions.

How do you write multiple conditions in a single IF statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

Can you use && and || together?

The logical operators && ("and") and || ("or") combine conditional expressions; the ! ("not") operator negates them. The ! has the highest precedence, then && , then || ; you will need parentheses to force a different order.


2 Answers

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)) {     ... } 
like image 82
48klocs Avatar answered Sep 30 '22 07:09

48klocs


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
like image 28
Paul Sasik Avatar answered Sep 30 '22 09:09

Paul Sasik