Reputation: 19
I'm writing some code where I have made a few methods and have put all of them in a list however I want the user to be able to choose a method from the list and then run that method as i dont want all the methods to run and only output the answer of chosen method as this is inefficient.
class program
{
//arrays
static void Arrays()
{
Console.WriteLine("Enter number of cars:");
Console.ReadKey();
}
// List
static void List()
{
Console.WriteLine("Enter items for shopping list");
shoppingList.Add("Apples");
shoppingList.Add("oranges");
shoppingList.Add("milk");
shoppingList.Add("butter");
Console.ReadKey();
}
static void Main(string[] strings)
{
List<Action> methods = new List<Action>();
methods.Add(Arrays);
methods.Add(List);
Console.WriteLine("what method do you want:");
string answer = Console.ReadLine();
foreach (Action a in methods.Where(//one of the methods == answer));
Console.WriteLine(//the method that is == answer);
if (answer == //one methods in list)
{
Console.WriteLine(////the method that is == answer);
}
}
Upvotes: 0
Views: 100
Reputation: 460238
You could use a dictionary:
Dictionary<string, Action> methods = new(StringComparer.OrdinalIgnoreCase);
methods.Add(nameof(Arrays), Arrays);
methods.Add(nameof(List), List);
Console.WriteLine("what method do you want:");
string answer = Console.ReadLine();
if(methods.TryGetValue(answer, out Action doIt))
{
doIt();
}
Upvotes: 1