Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine || operators in condition statement [duplicate]

Tags:

c#

.net

Instead of

if (foo == "1" || foo == "5" || foo == "9" ... )  

I like to combine them similar to the following (which doesn't work):

if (foo == ("1" || "5" || "9" ... )) 

Is that possible?

like image 500
KMC Avatar asked Jul 23 '13 16:07

KMC


People also ask

Can you use both || and &&?

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.

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

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

How many conditions can an if statement have in C?

Technically only 1 condition is evaluated inside an if , what is ascually happening is 1 condition gets evaluated and its result is evaluated with the next and so on...


1 Answers

Unfortunately not, your best bet is to create an extension method

public static bool IsOneOf<T>(this T value, params T[] options) {     return options.Contains(value); } 

and you can use it like this:

if (foo.IsOneOf("1", "5", "9")) {     ... } 

Being generic, it can be used for any type (int, string etc).

like image 148
Trevor Pilley Avatar answered Nov 10 '22 08:11

Trevor Pilley