簡體   English   中英

從通用列表中刪除項目

[英]Remove Item from generic list

我正在嘗試使用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
}

我知道可以通過將項目復制到另一個列表等方式來執行另一種操作,但是所有測試均顯示上述代碼確實刪除了第一項,但視圖並未反映出這一點。

有任何想法嗎?

每當您刪除項目時索引都會更改。 例如,刪除第0個項目后,第一個項目即為第0個項目。 為了防止這種情況從最后到開頭刪除項目:

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

這可能聽起來很傻,但你的結果是否有可能被其他地方覆蓋?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM