Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a variable to multiple values [duplicate]

Tags:

c#

Quite often in my code I need to compare a variable to several values :

if ( type == BillType.Bill || type == BillType.Payment || type == BillType.Receipt ) {   // Do stuff } 

I keep on thinking I can do :

if ( type in ( BillType.Bill, BillType.Payment, BillType.Receipt ) ) {    // Do stuff } 

But of course thats SQL that allows this.

Is there a tidier way in C#?

like image 233
Mongus Pong Avatar asked Mar 01 '10 15:03

Mongus Pong


People also ask

How do you compare variables with multiple values?

Use scatterplots to compare two continuous variables. Use scatterplot matrices to compare several pairs of continuous variables. Use side-by-side box plots to compare one continuous and one categorical variable. Use variability charts to compare one continuous Y variable to one or more categorical X variables.

How do you compare three variables in CPP?

To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.

How do you make a variable equal multiple values in Python?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value.


2 Answers

You could do with with .Contains like this:

if (new[] { BillType.Receipt, BillType.Bill, BillType.Payment}.Contains(type)) {} 

Or, create your own extension method that does it with a more readable syntax

public static class MyExtensions {     public static bool IsIn<T>(this T @this, params T[] possibles)     {         return possibles.Contains(@this);     } } 

Then call it by:

if (type.IsIn(BillType.Receipt, BillType.Bill, BillType.Payment)) {} 
like image 78
Mark Avatar answered Oct 25 '22 02:10

Mark


There's also the switch statement

switch(type) {     case BillType.Bill:     case BillType.Payment:     case BillType.Receipt:         // Do stuff         break; } 
like image 27
wasatz Avatar answered Oct 25 '22 01:10

wasatz