从通用列表中删除项目

Ali*_*liK 2 c# asp.net asp.net-mvc

我试图使用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
}
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

Sin*_*ian 7

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

foreach(int item in removeitems.OrderByDescending(n => n))
{
    model.ListItems.RemoveAt(item);
}
Run Code Online (Sandbox Code Playgroud)