2

I'm wondering if there is a short way to compare one Char to many Chars. In my code I read a Key for Yes or No [Y/N] then i will check if the Char is 'Y' Or 'N'.

This is the Long Way:

if(myChar == 'n' || myChar == 'y')
{
....

It tried(didn't work):

if(myChar == ('n'|'y'))
{
.....

Can someone help?

Mr Sausage
  • 21
  • 1
  • 2
  • 1
    I mean, if its just two expressions I don't see why you would need any short hand. An alternative would be to have an array of "allowed chars" and do a `Contains()`, but that seems overkill for something like this. – maccettura Jun 26 '17 at 15:04
  • The long way is the best way in this case, imo. – Alex K. Jun 26 '17 at 15:09

2 Answers2

4

Try looking in a collection:

HashSet<char> valid = new HashSet<char>() {
  'y', 'n', 'N', 'Y',
};

...

if (valid.Contains(myChar)) {
  ...
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

When the list of characters is short, use Contains method of string:

if ("yn".Contains(myChar)) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Note, this will be a case sensitive compare. You will need to do `"YyNn".Contains(myChar)` or use `"yn".IndexOf(myChar, StringComparison.OrdinalIgnoreCase) >= 0)` – Scott Chamberlain Jun 26 '17 at 15:50
  • @ScottChamberlain This is absolutely true, if OP needs case-insensitive comparison, he would need to do one of the methods that you described. – Sergey Kalinichenko Jun 26 '17 at 16:09