0

Is there a shortcut for comparing multiple values such as in the following expression?

if (choice == "a" || choice == "b" || choice == "c") {do something;}

I thought about switch statements, but they only work for single values as far as I know.

And what about variable declaration or constants?

int initialValue = 1, finalValue = 1;

  • Does this answer your question: https://stackoverflow.com/questions/12911691/switch-multiple-values-in-one-case/12911729? – Iliar Turdushev May 19 '20 at 08:51
  • @IliarTurdushev and what about if those values are not numerical? –  May 19 '20 at 08:54
  • Any constant value can be used in a `switch` `case`. – Johnathan Barclay May 19 '20 at 08:57
  • @IliarTurdushev and also, when they have a range of values, they must write it like this `age > 9 && age < 15` rather than just simply having `9 < age < 15` which in my opinion, is much more readable. –  May 19 '20 at 09:01
  • @JohnathanBarclay what about a range of values? Probably not good practice to write them one by one. Could I rewrite this `age > 9 && age < 15` as something like this `9 < age < 15` which is much more readable in my opinion. –  May 19 '20 at 09:03
  • You could write `9 < age && age < 15`. – Johnathan Barclay May 19 '20 at 09:05

2 Answers2

1

You can try Any()

public static string[] array = new string[] {"a", "b", "c"};
if(array.Any(x => x == choice))
{
   //Your business logic
}

Or you can try Any() with .Contains,

if(array.Any(choice.Contains))
{
   //Your business logic
}

You can use HashSet<T> to store distinct elements and use .Contains() to figure out choice is available in hashet or not

public static HashSet<string> array = new HashSet<string>(){"a", "b", "c"};
if(array.Contains(choice))
{
   Console.WriteLine("Implement your business logic");
}

.Net Fiddle

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

You can stack the case statements in order to map multiple values to the same action:

switch(choice)
{
  case "a":
  case "b":
  case "c":
    // Do something
    break;

  default:
    // Do something else
    break;
}
Sean
  • 60,939
  • 11
  • 97
  • 136
  • I guess, this would work for this case, but what about a range of numbers or more values? –  May 19 '20 at 09:05