KlappDaddy
KlappDaddy

Reputation: 27

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

Upvotes: 0

Views: 1376

Answers (3)

Fabio
Fabio

Reputation: 32445

dictionary.Keys and dictionary.Values returns collection of keys or values.
Console.WriteLine formats values by calling .ToString().

So you got exactly what your code is doing

dict.Keys.ToString()   
// System.Collections.Generic.Dictionary2+KeyCollection[System.String,System.String]

dict.Values.ToString()   
// System.Collections.Generic.Dictionary2+ValueCollection[System.String,System.String]

When you iterating through dictionary, on every iteration you will get instance of type KeyValuePair which contains key and correspondent value. That is why you should use iteration item for accessing required values

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

Upvotes: 1

Mostafiz
Mostafiz

Reputation: 7352

Basically you are iterating a collection called dict and during iteration inside foreach loop you are taking each element of the dict collection to item variable. And the problem of your code is dict is a collection so you cannot access it's property as like a single element. Better you change your code like

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

Upvotes: 2

Gregg
Gregg

Reputation: 625

Change your WriteLine to this:

 Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);

Upvotes: 0

Related Questions