c# - 我可以用字符串变量(或其他东西)命名数组的每个元素吗?

标签 c# arrays

我想给数组的每个元素命名。

这是我的代码:

string[] myArray = new string[5];

bool open = true;

while (open == true)
{
    Console.WriteLine(
    "Choose a number\n" +
    "[1] Put in 5 names\n" +
    "[2] Show all 5 names\n" +
    "[3] Close\n");

    Int32.TryParse(Console.ReadLine(), out int menu);

    switch (menu)
    {
        case 1:

            Console.WriteLine("\nWrite 5 letters\n");

            for (int i = 0; i < myArray.Length; i++)
            {
                myArray[i] = Console.ReadLine();
            }

            Console.ReadLine();
            break;

        case 2:

            Console.WriteLine("\nThese are the 5 letters:\n");

            for (int i = 0; i < myArray.Length; i++)
             {
                 Console.WriteLine(myArray[i]);
             }

             Console.ReadLine();
             break;

        case 3:

            open = false;
            break;
 }

我想要做的是,而不是像这样打印出数组(如果我将元素命名为 a、b、c、d、e):

a
b
c
d
e

我想在每个元素前面加上一个名字, 像这样:

[slot 1]: a
[slot 2]: b
[slot 3]: c
[slot 4]: d
[slot 5]: e

我还希望能够通过键入如下内容来打印出这封信:Console.WriteLine([slot 1]);
或者我必须写什么。

最佳答案

您正在寻找 Dictionary<String, String> ,不是数组。

var myDict = Dictionary<String, String>();

myDict["slot 1"] = "a";
myDict["slot 2"] = "b";

var x = myDict["slot 1"];

if (myDict.ContainsKey("slot 3"))
{
    Console.WriteLine(myDict["slot 3"]);
}

等等

关于c# - 我可以用字符串变量(或其他东西)命名数组的每个元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46368304/

相关文章:

c# - Linq 查询中的匿名类型与元组,性能注意事项

c - 如何在运行时在 C 中声明数组的大小?

javascript - 检查一个字符在字符串中出现了多少次

c# - 如何在 Visual Studio 2013 中进行并行构建?

c# - 从 .NET 使用 SAP Web 服务会抛出异常 ServiceModel.FaultException

c# - 根据包含ID的列表选择项目

c# - 使用任务并行库构建任务处理管道

arrays - 为什么,如果 MATLAB 是列优先的,某些函数会输出行向量?

python - 扩展数据类型?列表和关系的最佳数据结构?

arrays - Matlab : expandable array, 丢失数据