KlappDaddy KlappDaddy - 3 years ago 180
C# Question

c# foreach loop iterating through dictionary not giving correct output

Dictionary<string, string> dict = new Dictionary<string,string>();
dict.Add("Hello", "Goodbye");
dict.Add("Morning", "Evening");
dict.Add("Blue", "Red");

foreach(KeyValuePair<string,string> item in dict)
{
Console.WriteLine("Key = {0}, Value = {1}", dict.Keys, dict.Values);
}
Console.ReadLine();


Looking to get the keys and values as the output, but am getting the following:


Key =
System.Collections.Generic.Dictionary2+KeyCollection[System.String,System.String],
Value =
System.Collections.Generic.Dictionary2+ValueCollection[System.String,System.String]
Key =
System.Collections.Generic.Dictionary2+KeyCollection[System.String,System.String],
Value =
System.Collections.Generic.Dictionary2+ValueCollection[System.String,System.String]
Key =
System.Collections.Generic.Dictionary2+KeyCollection[System.String,System.String],
Value =
System.Collections.Generic.Dictionary2+ValueCollection[System.String,System.String]


Any advice on getting in the right direction would be great, followed the documentation on https://msdn.microsoft.com/en-us/library/bb346997(v=vs.110).aspx

Answer Source

Change your WriteLine to this:

 Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download