• Dictionary的遍历和修改


     

            /// <summary>
            /// 初始化一个Dic
            /// </summary>
            public static void mainTest()
            {
                Dictionary<String, Int32> dic = new Dictionary<String, Int32>();
                dic.Add("1", 1);
                dic.Add("2", 2);
                dic.Add("3", 3);
    
                Console.WriteLine("Org=============");
                foreachTravelDic(dic);
    
                modifyDic1(dic);
                Console.WriteLine("modify1=============");
                foreachTravelDic(dic);
    
    
                modifyDic2(dic);
                Console.WriteLine("modify2=============");
                foreachTravelDic(dic);
    
                Console.ReadKey();
            }

     

            /// <summary>
            /// foreach遍历Dictionary
            /// </summary>
            /// <param name="dic"></param>
            public static void foreachTravelDic(Dictionary<String, Int32> dic)
            {
                foreach (KeyValuePair<String, Int32> kvp in dic)
                {
                    Console.WriteLine(String.Format("Key:{0}; Value:{1}", kvp.Key, kvp.Value));
                    //dic[kvp.Key] = 2;//此操作会报错
                }
            }
    
    
            /// <summary>
            ///使用dic.Keys.ToArray方法遍历时更改Dic
            /// </summary>
            /// <param name="dic"></param>
            private static void modifyDic2(Dictionary<String, Int32> dic)
            {
                String[] keyStr = dic.Keys.ToArray<String>();
                for (int i = 0; i < keyStr.Length; i++)
                {
                    dic[keyStr[i]] = dic[keyStr[i]] + 22;
                }
            }
    
            /// <summary>
            /// 使用dic.Keys.CopyTo方法遍历时更改Dic
            /// </summary>
            /// <param name="dic"></param>
            private static void modifyDic1(Dictionary<String, Int32> dic)
            {
                int dicCount = dic.Keys.Count;
                String[] strKey = new String[dicCount];
                dic.Keys.CopyTo(strKey, 0);//支持.net2.0
                for (int i = 0; i < strKey.Length; i++)
                {
                    if (dic.ContainsKey(strKey[i]))
                    {
                        dic[strKey[i]] = dic[strKey[i]] + 11;
                    }
                }
            }

     

    output:

    Org=============
    Key:1; Value:1
    Key:2; Value:2
    Key:3; Value:3
    modify1=============
    Key:1; Value:12
    Key:2; Value:13
    Key:3; Value:14
    modify2=============
    Key:1; Value:34
    Key:2; Value:35
    Key:3; Value:36

  • 相关阅读:
    图片压缩后,依然很大的解决方案
    怎么使用javascript实现类的功能
    javascript实现像java、c#之类的sleep暂停的函数功能
    用ajax和asp.net实现智能搜索功能
    insert into 和insert into select性能比较
    百度编辑器
    document.selection.createRange()
    CSS设置透明效果
    class中一个小技巧
    asp.net中 解析JSON
  • 原文地址:https://www.cnblogs.com/softidea/p/3342941.html
Copyright © 2020-2023  润新知