我想为数组的每个元素命名。
这是我的代码:
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]);
或者我要写的东西。
答案 0 :(得分:3)
您正在寻找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"]);
}
等
答案 1 :(得分:2)
您可以使用Dictionary<string, string>
之类的:
var myDic = new Dictionary<string, string>();
myDic.Add("foo", "bar");
var value = myDic["foo"];
小心使用词典,key
“foo”在字典中必须是唯一的!
否则,您可以使用List<KeyValuePair<string, string>>
之类的:
var myList = new List<KeyValuePair<string, string>>();
myList.Add(new KeyValuePair<string, string>("foo", "bar"));
var value = myList.First(p=>p.Key == "foo");
答案 2 :(得分:0)
在其他答案的帮助下,我设法找到了解决问题的方法。 这就是我所做的,希望它对某人有帮助!
string[] myArray = new string[5];
var mySlot = new Dictionary<int, string>();
mySlot.Add(1, "Slot 1");
mySlot.Add(2, "Slot 2");
mySlot.Add(3, "Slot 3");
mySlot.Add(4, "Slot 4");
mySlot.Add(5, "Slot 5");
bool open = true;
while (open == true)
{
Console.WriteLine(
"Choose a number\n" +
"[1] Put in 5 letters\n" +
"[2] Show all 5 letters\n" +
"[3] Close\n");
Int32.TryParse(Console.ReadLine(), out int menu);
switch (menu)
{
case 1:
for (int i = 0; i < myArray.Length; i++)
{
Console.Write(mySlot.ElementAt(i).Value + ": ");
myArray[i] = Console.ReadLine();
}
break;
case 2:
Console.Write("These are the 5 letters:\n\n" +
mySlot[1] + ": " + myArray[0] + "\n" +
mySlot[2] + ": " + myArray[1] + "\n" +
mySlot[3] + ": " + myArray[2] + "\n" +
mySlot[4] + ": " + myArray[3] + "\n" +
mySlot[5] + ": " + myArray[4]);
Console.ReadLine();
break;
case 3:
open = false;
break;
}
如果我使用a,b,c,d,e来填充我的数组,则会打印出来:
These are the 5 letters:
Slot 1: a
Slot 2: b
Slot 3: c
Slot 4: d
Slot 5: e