Reputation: 1067
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?
Upvotes: 2
Views: 2108
Reputation: 16286
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);
}
Upvotes: 7
Reputation: 4782
This may sound quite silly, but is it possible that your result is being overwritten from somewhere else?
Upvotes: 0