/// <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
摘自:http://www.cnblogs.com/softidea/archive/2013/09/27/3342941.html