2008年7月14日 星期一

刪除List中的某些Item

要使用迴圈的方式刪除List中的某幾個Item時必須注意
迴圈中的index值應由最後面, 依序判斷至最前面
假設有一List如下:
List.Items[0] = "A";
List,Items[1] = "A";
List.Items[2] = "B";
List.Items[3] = "C";
若要將值為 "A" 的 Item 從 List 中移除,可以使用for迴圈來判斷
一般使用錯誤的方式如下:
for ( int index = 0; index <
List.Items.Count; index++ )
{

  if ( List.Items[index] == "A" )
    List.Items.RemoveAt ( index );
}
應注意的是,
當 index = 0 的時候, 會執行
List.Items.RemoveAt(index);
這時 List 的內容將會如下:
List,Items[0] = "A";
List.Items[1] = "B";
List.Items[2] = "C";

繼續在下一個迴圈,
當 index = 1 的時候, 我們看到此時
List.Items[index] 為 "B"
這表示第2個"A" 被跳過了, 想當然最後的結果是錯誤的.

因此我們應該將程式改為下面的方式:
for ( int index = List.Items.Count - 1; index > 0; index-- )
{
  if ( List.Items[index] == "A" )
    List.Items.RemoveAt ( index );
}

沒有留言:

張貼留言