简体   繁体   中英

Remove Item from generic list

I am trying to remove an item from a generic list using RemoveAt. The odd thing is while using the debugger I can see my item has been removed and yet when passing it to a view the item removed is showing up but the last item has been removed.

Code looks like this

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
}

I understand that I can do it another way by copying the items into another list etc, but all tests show the above code does remove the first item and yet the view does not reflect this.

Any ideas?

Whenever you remove items the indexes change. For example after you remove the 0th item, the item which was the 1st item will now be the 0th. To prevent this remove items from the end towards the beginning:

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

这可能听起来很傻,但你的结果是否有可能被其他地方覆盖?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM