.NET Dictionary foreach的存取問題

在.NET 3.5使用Dictionary時,遇到了一個問題。
程式碼如下,

//定義Dictionary的內容
Dictionary<string, int> dict = new Dictionary<string, int>()
{
       {"first", 1}, {"second", 2}, {"third", 3},
       {"fourth", 4}, {"fifth", 5}
};

//把Dictionary內,所有的值改為數字0
foreach (KeyValuePair<string, int> kvp in dict)
       dict[kvp.Key] = 0;

上面這套程式會出現以下的錯誤訊息,
InvalidOperationException 集合已修改; 列舉作業可能尚未執行。

查看MSDN的說明後後發現,使用foreach走訪Dictionary時,只能讀取,不能改變內容。

The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

於是把程式碼改寫如下,
先將Dictionary的key全部取出,再用for loop修改Dictionary的內容。

Dictionary<string, int> dict = new Dictionary<string, int>()
{
      {"first", 1}, {"second", 2}, {"third", 3},
      {"fourth", 4}, {"fifth", 5}
};

//把Dictionary的所有key放到陣列中
string[] keyArr = new string[dict.Keys.Count];

int counter = 0;
foreach (string s in dict.Keys)
{
      keyArr[counter] = s;
      counter++;
}

//利用陣列改變Dictionary的內容
for (counter = 0; counter < keyArr.Length; counter++)
{
      dict[keyArr[counter]] = 0;
      System.Console.WriteLine("Key = " + keyArr[counter] + " Value = " + dict[keyArr[counter]].ToString());
]

以上,做為記錄。

發表留言