[英]Can I name each element of an array with string variables (or something else)?
我想给数组的每个元素命名。
这是我的代码:
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"]);
}
等等
您可以使用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");
在其他答案的帮助下,我设法找到了解决问题的方法。 这就是我所做的,希望对您有所帮助!
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.