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
}

我知道我可以通过将项目复制到另一个列表等来以另一种方式做到这一点,但是所有测试都显示上面的代码确实删除了第一个项目,但视图并没有反映这一点。

有任何想法吗?

4

2 回答 2

7

每当您删除项目时,索引都会更改。例如,在您删除第 0 个项目后,作为第 1 个项目的项目现在将成为第 0 个项目。为了防止这种情况从头到尾删除项目:

foreach(int item in removeitems.OrderByDescending(n => n))
{
    model.ListItems.RemoveAt(item);
}
于 2013-05-12T05:44:24.280 回答
0

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

于 2013-05-12T05:39:32.300 回答