Reputation: 33
I would like to give names to each element of an array.
This is my code:
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;
}
What I want to do is so that instead of printing out the array (if I name the elements a,b,c,d,e) like this:
a
b
c
d
e
I want to put a name infront of each element, something like this:
[slot 1]: a
[slot 2]: b
[slot 3]: c
[slot 4]: d
[slot 5]: e
I also wanna be able to print out the letter by typing something like: Console.WriteLine([slot 1]);
or what ever I have to write.
Upvotes: 2
Views: 633
Reputation: 33
With help from the other answers I managed to find a solution to my problem. This is what I did, hope it helps someone!
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;
}
If I use a,b,c,d,e to fill my array, this gets printed:
These are the 5 letters:
Slot 1: a
Slot 2: b
Slot 3: c
Slot 4: d
Slot 5: e
Upvotes: 0
Reputation: 2748
You can use Dictionary<string, string>
like :
var myDic = new Dictionary<string, string>();
myDic.Add("foo", "bar");
var value = myDic["foo"];
Be careful with Dictionary, the key
"foo" must be unique in the dictionary !
Otherwise, you can use List<KeyValuePair<string, string>>
like :
var myList = new List<KeyValuePair<string, string>>();
myList.Add(new KeyValuePair<string, string>("foo", "bar"));
var value = myList.First(p=>p.Key == "foo");
Upvotes: 2
Reputation: 37066
You're looking for a Dictionary<String, String>
, not an array.
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"]);
}
etc.
Upvotes: 4