[英]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.