2013-05-12 152 views
2

我正嘗試使用RemoveAt從通用列表中刪除項目。奇怪的是,在使用調試器的時候,我可以看到我的物品已被移除,但是當它傳遞給視圖時,移除的物品顯示出來,但最後一個物品已被移除。從通用列表中刪除項目

代碼看起來像這樣

public ActionResult(MyModel model, int[] removeitems) 
{ 
//model.ListItems has 10 items 
//Incoming removeitems has 0 as the first item to remove as a test 
foreach(int item in removeitems) 
{ 
model.ListItems.RemoveAt(item); 
} 
//by this time debugger shows that item 0 has in fact been removed and no longer exists in the list 
return View(model); 
//after the view is rendered it shows item 0 is still there but 10 has been removed 
} 

我知道我可以通過複製項目到另一個列表等做另一種方式,但所有的測試表明,上面的代碼不會刪除的第一個項目,但認爲不不反映這一點。

任何想法?

+2

後您的視圖代碼....我認爲,有鑑於代碼一些邪惡的一部分.... – 2013-05-12 05:42:15

+0

你確定你不想' .Remove()'找到元素並將其刪除?那麼找到第一個匹配元素並將其刪除。 – Nomad101 2013-05-12 05:44:25

+0

@ Nomad101我感謝我知道刪除它不是我想要的 – AliK 2013-05-12 05:49:03

回答

6

每當您刪除項目索引更改。例如,在刪除第0項後,第1項的項目現在爲第0項。爲了防止這種情況最終刪除項目向開頭:

foreach(int item in removeitems.OrderByDescending(n => n)) 
{ 
    model.ListItems.RemoveAt(item); 
} 
+0

感謝它的工作,出於興趣沒有人知道爲什麼調試器和測試工作,而視圖不是? – AliK 2013-05-12 06:02:48

+0

@AliK這取決於測試。如果'removeitems'只包含1個項目,或者它已經按降序排序,則不會失敗。 – 2013-05-12 06:05:25

0

這聽起來很愚蠢,但是有可能你的結果被其他地方覆蓋了嗎?

+0

我確實考慮過這一點,並且可以確定情況並非如此,因爲我的觀點很簡單,只是列出了列表中的項目。 – AliK 2013-05-12 05:43:12