Search code examples
c#dictionarylookupcontainskeytrygetvalue

How do I output my Dictionary<string, Dictionary<string, string>>?


I'm really stuck here now with my Dictionary Output:

I have this Code to "fill" the dictionary (basically there are 2 of them):

Dictionary<string, Dictionary<string, string>> newDictionary = new Dictionary<string,Dictionary<string, string>>();

Form1 _form1Object = new Form1();

foreach (SectionData section  in data.Sections) {
    var keyDictionary = new Dictionary<string, string>();                  

    foreach (KeyData key in section.Keys)
        keyDictionary.Add(key.KeyName.ToString(), key.Value.ToString());

    newDictionary.Add(section.SectionName.ToString(), keyDictionary);
}

This works pretty well, but now I would like to search through it. That means I have a String which stores a "selection" from the "combobox" in Form1.class I have.

Now I want to lookup that String in my Dictionary, for that I have the following:

while (_form1Object.comboBox2.SelectedIndex > -1)
{
     _form1Object.SelectedItemName = _form1Object.comboBox2.SelectedItem.ToString();

     if (newDictionary.ContainsKey(_form1Object.SelectedItemName))
     {
         Console.WriteLine("Key: {0}, Value: {1}", newDictionary[_form1Object.SelectedItemName]);
         Console.WriteLine("Dictionary includes 'SelectedItem' but there is no output");
     }
     else Console.WriteLine("Couldn't check Selected Name");
}

But, yes you're right, it doesn't work, the output in the console is:

System.Collections.Generic.Dictionary`2[System.String,System.String]

And I even don't get any of my Console.WriteLine("Couln't check selected Name") So that mean it will run through the IF statement but the Console.WriteLine function is not working.

Now my question, how do I lookup my String SelectedItemName in the Dictionary<string, Dictionary<string,string>>?


Solution

  • You'll have to implement your own output logic. Dictionary<TKey, TValue> does not override Object.ToString so the output is just the class name. Something like:

    public static class DictionaryExtensions
    { 
      public static string WriteContent(this Dictionary<string, string> source)
      {
        var sb = new StringBuilder();
        foreach (var kvp in source) {
          sb.AddLine("Key: {0} Value: {1}", kvp.Key, kvp.Value);
        }
        return sb.ToString();
      }
    }
    

    Will allow you to just call .WriteContent() on newDictionary[_form1object.SelectedItemName] when that namespace is referenced.