通常的C#循环遍历是用foreach循环遍历。好处就是简单,但是缺点就是无法在循环中改变Dictionary的值。
Dictionary <string,int>
一下遍历这个Dictionary。
代码:
for (int i = 0; i < HostMessage.Count; i++)
{
var item = HostMessage.ElementAt(i);
Console.WriteLine("key is " + item.Key);
Console.WriteLine("value is " + item.Value);
if (item.Key == "MS01")
{
HostMessage["MT01"] = 102;
}
}
默认HostMessage中有值。
这样就可以了。
我这样写有个BUG,就是在终端输出依旧是没有改变值的,其实是改变了,是不过没有及时输出。要是用以下代码就好了。
for (int i = 0; i < HostMessage.Count; i++)
{
var item = HostMessage.ElementAt(i);
Console.WriteLine("key is " + item.Key);
Console.WriteLine("value is " + item.Value);
if (item.Key == "MS01")
{
HostMessage["MT01"] = 102;
}
}
Console.WriteLine("*****************************8888");
foreach (string key in HostMessage.Keys)
{
Console.WriteLine("Key = {0}, Value = {1}", key, HostMessage[key]);
}
-------------------------------------20200810------------------------------------------------------------------------------
更新一个新用法
Dictionary<Dictionary<string, int>, string> zh = new Dictionary<Dictionary<string, int>, string>();
如何输出这个字典?
直接上示例代码
Dictionary<Dictionary<string, int>, string> zh = new Dictionary<Dictionary<string, int>, string>();
Dictionary<string, int> HostM = new Dictionary<string, int>();
Dictionary<string, string> ss = new Dictionary<string, string>();
HostM.Add("MT01", 101);
HostM.Add("MT09",100);
HostM.Add("MT010", 101);
HostM.Add("MT02", 100);
HostM.Add("MT03", 101);
HostM.Add("MT04", 100);
HostM.Add("MT05", 101);
HostM.Add("MT08", 100);
HostM.Add("Ms01", 101);
HostM.Add("Ms02", 100);
HostM.Add("LD01", 101);
HostM.Add("PS01", 100);
ss.Add("MT01", "traytab");
ss.Add("MT09", "solidifyOut");
ss.Add("MT010", "solidifyIn");
ss.Add("MT02", "WBIn");
ss.Add("MT03", "WBOUt");
ss.Add("MT04", "Finish");
ss.Add("MT05", "are");
ss.Add("MT08", "spc");
ss.Add("Ms01", "LDmachine");
ss.Add("Ms02", "qwe");
ss.Add("LD01", "asc");
ss.Add("PS01", "sdf");
foreach (string key in HostM.Keys)
{
Dictionary<string, int> ac = new Dictionary<string, int>();
ac.Add(key, HostM[key]);
zh.Add(ac, ss[key]);
}
foreach (Dictionary<string, int> key in zh.Keys)
{
foreach (string kkey in key.Keys)
{
Console.WriteLine(kkey + "_" + key[kkey] + "_" + zh[key]);
}
这样就可以了。
前面的都是给字典添加内容的,就不说了,解释最后三行代码
foreach (Dictionary<string, int> key in zh.Keys)
{
foreach (string kkey in key.Keys)
{
Console.WriteLine(kkey + "_" + key[kkey] + "_" + zh[key]);
}
第一行,因为zh的key是一个字典,所以foreach的key要设置为Dictionary<string, int> ,第二foreach的kkey因为Dictionary<string, int> 的key是string,所以设置kkey为string。
这样思路就清晰了,kkey是(Dictionary<string, int> 的key(键)key是Dictionary<string, int>字典,所以值为key[kkey].zh[key]为最外围的字典内容。这样只要思路理清了,就输出正确了。
我在这里绕了好久才想明白。