我常用的解決辦法是做壹份拷貝,遍歷這個拷貝。(如果數據不是很大的話)
比如,這個代碼:
C#代碼
1.<SPAN style="FONT-SIZE: x-small">IDictionary<int, string> ht = new Dictionary<int, string>();
2.ht.Add(1, "one");
3.ht.Add(2, "two");
4.
5.// Print "one,two"
6.Console.WriteLine(String.Join(",", ht.Values.Select(i => i.ToString()).ToArray()));
7.
8.foreach (int key in new List<int>(ht.Keys)) {
9. if (key == 1) ht.Remove(key);
10.}
11.
12.// Print "two"
13.Console.WriteLine(String.Join(",", ht.Values.Select(i => i.ToString()).ToArray()));</SPAN>
IDictionary<int, string> ht = new Dictionary<int, string>();
ht.Add(1, "one");
ht.Add(2, "two");
// Print "one,two"
Console.WriteLine(String.Join(",", ht.Values.Select(i => i.ToString()).ToArray()));
foreach (int key in new List<int>(ht.Keys)) {
if (key == 1) ht.Remove(key);
}
// Print "two"
Console.WriteLine(String.Join(",", ht.Values.Select(i => i.ToString()).ToArray())); 我在遍歷的時候,做了壹份拷貝。代碼是 new List<int>(ht.Keys),用到了 List 的構造拷貝函數,