关于dictionary的一些问题

好久没有来博客园了

我想告诉大家,我乾坤又回来了

今天发一段小小的关于dictionary的代码

出现原因

我想遍历dic中的数据,然后对value进行操作

结果直接挂掉了

原因分析

在对dic遍历的时候其值是只读的不可修改

如果想对其进行修改可以找个替身,最后用替身就好了

demo
 1     //first we need a dic
 2             Dictionary<int, int> dic = new Dictionary<int, int>();
 3             dic.Add(1, 1);
 4             dic.Add(2,2);
 5     //here define a replacement
 6             Dictionary<int, int> dic2 = new Dictionary<int, int>();
 7    //add the key and value of dic to dic2
 8             foreach (var item in dic)
 9             {
10                 dic2.Add(item.Key,item.Value);
11                 dic2[item.Key] = dic2[item.Key] - 1;
12             }
13   // we get resoult
14             foreach (var item in dic2)
15             {
16                 Console.WriteLine(item.Key);
17                 Console.WriteLine(item.Value);
18             }    

最后替身替代原始dic即可
我是小白,请多多指教

posted @ 2013-01-18 00:37  冰雪乾坤  阅读(221)  评论(0编辑  收藏  举报