首页 > 解决方案 > 我如何让用户在 C# 中以他们希望的任何顺序在 5 个项目之间进行选择?

问题描述

我试图在控制台上为我的用户提供 5 个选项,我希望他们能够从菜单中选择多个选项。我计算出用户可以在 5 种选择中选择 31 种方式。我试图为它写一个开关/案例,但为它写 31 个案例似乎不合逻辑。还有其他方法吗?我会感谢你们帮我解决这个问题

namespace Homework_2
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("a-cake b-milk c-noodles d-cheese e-coke:");
            string choice = Console.ReadLine();
            switch (choice)
            {
                default:
                    break;
            }

        }
    }
}

标签: c#switch-statement

解决方案


您似乎想要求用户输入多个选项,然后对这些选项进行一些操作。您似乎也有与每个项目相关的价格/成本,所以我会考虑3-Tuple在这种情况下使用 a。

var options = new List<Tuple<int, string, int>>
{
    Tuple.Create( 1, "Cake", 100 ),
    Tuple.Create( 2, "Milk", 200 ),
    Tuple.Create( 3, "Noodles", 300 ),
    Tuple.Create( 4, "Cheese", 400 ),
    Tuple.Create( 5, "Coke", 500 )
};

第一个是您希望用户输入的选项,第二个是项目名称,第三个是单价。

然后要求用户输入他们的选择,用逗号分隔:

Console.WriteLine("Select one or more options seperated by a comma");
foreach (var opt in options)
{
    Console.WriteLine("{0} - {1}", opt.Item2, opt.Item1);
}
var selection = Console.ReadLine();

接下来,我们将用逗号分割用户输入并遍历它们。显然,如果你想要一个好的程序,你必须在这里进行错误处理,以防用户输入错误,但这只是为了说明。

var items = selection.Split(',');
foreach (var item in items)
{
    if (int.TryParse(item, out int value))
    {
        // We're looking in the 'options' list if we have the selection the user made
        var option = options.FirstOrDefault(x => x.Item1 == value);
        if (option != null)
        {
            // If it does exist, do what you want with it. Here I'm merely printing them.
            Console.WriteLine("{0} - {1} - {2}", option.Item1, option.Item2, option.Item3);
        }
    }
}

推荐阅读