经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
C# 遍历Dictionary并修改其中的Value
来源:cnblogs  作者:forbetter223  时间:2018/11/28 9:58:50  对本文有异议

C#的Dictionary类型的值,知道key后,value可以修改吗?答案是肯定能修改的。我在遍历的过程中可以修改Value吗?答案是也是肯定能修改的,但是不能用For each循环。否则会报以下的Exception.

  1. System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'

之所以会报Exception是For each本身的问题,和Dictionary没关系。For each循环不能改变集合中各项的值,如果需要迭代并改变集合项中的值,请用For循环。

大家来看下例子:

  1. 1 // defined the Dictionary variable
  2. 2 Dictionary<int, string> td = new Dictionary<int, string>();
  3. 3 td.Add(1, "str1");
  4. 4 td.Add(2, "str2");
  5. 5 td.Add(3, "str3");
  6. 6 td.Add(4, "str4");
  7. 7 // test for
  8. 8 TestForDictionary(td);
  9. 9 // test for each
  10. 10 TestForEachDictionary(td);
  1. TestForDictionary Code
  1. 1 static void TestForDictionary(Dictionary<int, string> paramTd)
  2. 2 {
  3. 3
  4. 4 for (int i = 1;i<= paramTd.Keys.Count;i++)
  5. 5 {
  6. 6 paramTd[i] = "string" + i;
  7. 7 Console.WriteLine(paramTd[i]);
  8. 8 }
  9. 9 }
  1. TestForDictionary的执行结果
  1. string1
  2. string2
  3. string3
  4. string4
  1.  
  1. TestForEachDictionary Code
  1. 1 static void TestForEachDictionary(Dictionary<int, string> paramTd)
  2. 2 {
  3. 3 int forEachCnt = 1;
  4. 4 foreach (KeyValuePair<int,string> item in paramTd)//System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
  5. 5 {
  6. 6 paramTd[item.Key] = "forEach" + forEachCnt;
  7. 7 Console.WriteLine(paramTd[item.Key]);
  8. 8 forEachCnt += 1;
  9. 9 }
  10. 10 }
  1. TestForEachDictionary里的For each会在循环第二次的时候报错,也就是说它会在窗口中打印出“forEach1”后断掉。
  1.  
  1.  
  1.  

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号