我现在真的被字典输出卡在这里了:
我有这个代码来"填充"字典(基本上有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中"combobox"中的"selection"。
现在我想在我的字典中查找该字符串,为此我有以下内容:
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>>
中查找我的StringSelectedItemName?
您必须实现自己的输出逻辑。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();
}
}
将允许您在引用该命名空间时仅在newDictionary[_form1object.SelectedItemName]
上调用.WriteContent()
。
您需要类似的东西:
foreach (var keyValue in newDictionary[_form1Object.SelectedItemName])
{
Console.WriteLine("Key: {0}, Value: {1}", keyValue.Key, keyValue.Value);
}
它正在正常工作。看,你正在获取这个表达式
newDictionary[_form1Object.SelectedItemName]
其中CCD_ 7具有字符串关键字和另一字典作为值。因此,这个表达式将返回父字典的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);
}
}