简体   繁体   English

从通用列表中删除项目

[英]Remove Item from generic list

I am trying to remove an item from a generic list using RemoveAt. 我正在尝试使用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. 例如,删除第0个项目后,第一个项目即为第0个项目。 To prevent this remove items from the end towards the beginning: 为了防止这种情况从最后到开头删除项目:

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