所以我有一个复杂的字典:
Dictionary<string, Dictionary< string, HashSet< string >>>
如何打印其键和值?
答案 0 :(得分:1)
//example
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var dic = new Dictionary<string, Dictionary<string,HashSet<string>>>
{
{"k", new Dictionary<string,HashSet<string>>
{
{"k1", new HashSet<string>{"a","b","c"}}
}
},
{"k3", new Dictionary<string,HashSet<string>>
{
{"k4", new HashSet<string>{"1","2","3"}}
}
}
};
foreach(var p in dic)
{
Console.Write(p.Key + " -- ");
foreach(var p1 in p.Value)
{
Console.Write(p1.Key + " -- ");
foreach(var str in p1.Value)
{
Console.Write(str + " ");
}
}
Console.WriteLine();
}
}
}
output: k -- k1 -- a b c
k3 -- k4 -- 1 2 3
答案 1 :(得分:0)
要将所有值都放入字符串中,您可以使用此
Dictionary<string,string> dictionary;
//[...]
string output = "";
foreach(string key in dictionary.Keys)
{
output += "\nKey: \""+key+"\" Value: \""+dictionary[key]+"\"";
}
MessageBox.Show(output);
我想你想调整格式,但这应该会有所帮助。
答案 2 :(得分:0)
如果您的字典是这样的:
Dictionary<string, Dictionary<string, HashSet<string>>> myDic = new Dictionary<string, Dictionary<string, HashSet<string>>>();
然后你可以做这样的事情将所有结果都变成一个字符串,用新行分隔。
StringBuilder result = new StringBuilder();
foreach (KeyValuePair<string, Dictionary<string, HashSet<string>>> outerDictionaries in myDic)
{
foreach (KeyValuePair<string, HashSet<string>> innerDictionaries in outerDictionaries)
{
result.AppendLine(string.Format("OuterDictionaryKey: {0}, InnerDictionaryKey: {1}, InnerDictionaryValue: {2}", outerDictionaries.Key, innerDictionaries.Key, innerDictionaries.Value));
}
}