0

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

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

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

这工作得很好,但现在我想搜索它。这意味着我有一个字符串,它存储来自我拥有的 Form1.class 中的“组合框”的“选择”。

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

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 函数不起作用。

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

4

3 回答 3

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]引用该命名空间时调用。

于 2014-09-11T14:08:37.883 回答
1

你需要类似的东西:

foreach (var keyValue in newDictionary[_form1Object.SelectedItemName])
{
   Console.WriteLine("Key: {0}, Value: {1}", keyValue.Key, keyValue.Value);
}
于 2014-09-11T14:02:28.890 回答
1

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

newDictionary[_form1Object.SelectedItemName]

wherenewDictionary有一个字符串键和另一个字典作为值。所以这个表达式将返回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);
     }
 }
于 2014-09-11T14:03:04.550 回答