Referencing file contents in a switch case statement in C#/Mono?
-
30-09-2019 - |
Question
I'm setting up a menu system whereby a user is asked to pick a radio station from a list, and for ease of use down the road, I want that list to be in a file called StationList. That bit's all sorted, but I have a problem with the selection process.
Is there a way to have a case statement reference StationList for valid cases instead of having to type them all in manually? I've had a look around and there doesn't seem to be an immediate answer: bear in mind though that I've only been learning it for two weeks :)
Thanks in advance!
Example:
i = (an element from iterating through StationList)
switch (selection)
{
case (i):
i = (int)Choice.GoodChoice;
Console.WriteLine("You chose " + selection + " radio!");
break;
case "!exit":
case "!!":
i = (int)Choice.ExitChoice;
break;
case "!info":
TitleScreen();
Console.ForegroundColor = ConsoleColor.Green;
break;
default:
Console.WriteLine("Invalid selection! Please try again!");
break;
}
Solution
This is impossible.
Event if it were possible, imagine that you have your switch with cases automatically -- how would you define what to do in each of the case
s?
Edit:
You need just to be able to check if the selection is one of the strings from the list. So you need basically (1) add all your strings to a HashSet
, (2) you code will be like that:
HashSet hashset = new HashSet();
using (var file = new StreamReader(path))
{
string line;
while ((line = file.ReadLine()) != null)
hashset.Add(line);
}
// ...
if (hashset.Contains(selection))
{
i = (int)Choice.GoodChoice;
Console.WriteLine("You chose " + selection + " radio!");
}
else
{
switch (selection)
{
case "!exit":
case "!!":
i = (int)Choice.ExitChoice;
break;
case "!info":
TitleScreen();
Console.ForegroundColor = ConsoleColor.Green;
break;
default:
Console.WriteLine("Invalid selection! Please try again!");
break;
}
}