当前位置: 移动技术网 > IT编程>开发语言>.net > C# 遍历Dictionary并修改其中的Value

C# 遍历Dictionary并修改其中的Value

2018年11月28日  | 移动技术网IT编程  | 我要评论

尿布性皮炎,香港苹果官网中文,9018电影网

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

system.invalidoperationexception: 'collection was modified; enumeration operation may not execute.'

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

大家来看下例子:

 1             // defined the dictionary variable
 2             dictionary<int, string> td = new dictionary<int, string>();
 3             td.add(1, "str1");
 4             td.add(2, "str2");
 5             td.add(3, "str3");
 6             td.add(4, "str4");
 7             // test for
 8             testfordictionary(td);
 9             // test for each
10             testforeachdictionary(td);
testfordictionary code
1         static void testfordictionary(dictionary<int, string> paramtd)
2         {
3             
4             for (int i = 1;i<= paramtd.keys.count;i++)
5             {
6                 paramtd[i] = "string" + i;
7                 console.writeline(paramtd[i]);
8             }
9         }
testfordictionary的执行结果
string1
string2
string3
string4

testforeachdictionary code
 1         static void testforeachdictionary(dictionary<int, string> paramtd)
 2         {
 3             int foreachcnt = 1;
 4             foreach (keyvaluepair<int,string> item in paramtd)//system.invalidoperationexception: 'collection was modified; enumeration operation may not execute.'
 5             {
 6                 paramtd[item.key] = "foreach" + foreachcnt;
 7                 console.writeline(paramtd[item.key]);
 8                 foreachcnt += 1;
 9             }
10         }
testforeachdictionary里的for each会在循环第二次的时候报错,也就是说它会在窗口中打印出“foreach1”后断掉。


 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网