如何输出我的Dictionary <string,dictionary <string,=“”string =“”>&gt;?</string,>

时间:2014-09-11 13:57:33

标签: c# dictionary lookup containskey trygetvalue

我现在真的被我的词典输出困在这里:

我有这个代码来“填写”字典(基本上有两个):

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);
}

这很好用,但现在我想搜索它。这意味着我有一个String,它存储了我在Form1.class中的“combobox”中的“选择”。

现在我想在我的词典中查找该字符串,因为我有以下内容:

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");
}

但是,是的,你是对的,它不起作用,控制台中的输出是:

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

我甚至没有得到任何Console.WriteLine("Couln't check selected Name")所以这意味着它将通过IF语句运行,但Console.WriteLine函数不起作用。

现在我的问题是,如何在Dictionary<string, Dictionary<string,string>>中查找我的String SelectedItemName?

3 个答案:

答案 0 :(得分:2)

您必须实现自己的输出逻辑。 Dictionary<TKey, TValue>不会覆盖Object.ToString,因此输出只是类名。类似的东西:

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();
  }
}

当引用该命名空间时,将允许您在.WriteContent()上调用newDictionary[_form1object.SelectedItemName]

答案 1 :(得分:1)

你需要类似的东西:

foreach (var keyValue in newDictionary[_form1Object.SelectedItemName])
{
   Console.WriteLine("Key: {0}, Value: {1}", keyValue.Key, keyValue.Value);
}

答案 2 :(得分:1)

它正常运作。看你正在取这个表达式

newDictionary[_form1Object.SelectedItemName]

其中newDictionary有一个字符串键,另一个字典作为值。因此,此表达式将返回父词典的value字段,实际上是dictionary

这意味着您还必须像这样迭代孩子词典

 if (newDictionary.ContainsKey(_form1Object.SelectedItemName))
 {
     Console.WriteLine("Parent Key : {0}",_form1Object.SelectedItemName)
     foreach(var childDict in newDictionary[_form1Object.SelectedItemName])
     {
        Console.WriteLine("Key: {0}, Value: {1}", childDict.Key,childDict.Value);
     }
 }