c# - 我如何让用户在 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;
}
}
}
}
解决方案
您似乎想要求用户输入多个选项,然后对这些选项进行一些操作。您似乎也有与每个项目相关的价格/成本,所以我会考虑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);
}
}
}
推荐阅读
- typescript - 编译导出以供导入和窗口使用
- reactjs - 如何根据错误和触摸状态设置 Formik 字段的样式
- python-3.x - 如何自省 PEP 484 类型提示?
- python - Python:hyp2f1 与 sympy 的符号使用
- reactjs - Codesandbox 为 React 应用程序提供“目标容器不是 DOM 元素”错误,但 webpack-dev-server 没有
- c# - 使用函数连接到本地 sql db 时键“attachdbfilename”的值无效
- python - 在 itertools.permutations 中将范围设置为参数
- mysql - MYSQL CONV 从十六进制到十进制问题
- jquery - 即使在 html 中生成,Kendo.Combobox 也不显示其选项
- c++ - 如何修复 C++ 中的随机字符输出?