问题描述
我有以下的方法,我想删除从我的收藏相匹配的产品ID的项目。似乎相当简单的,但我得到一个异常。基本上我的收藏越来越不同步。那么,什么是从集合中删除项目的最佳途径。
I have the following method, I wish to remove items from my collection that match the product Id. Seems fairly straight forward, but i get an exception. Basically my collection is getting out of sync. So what is the best way to remove an item from a collection.
public void RemoveOrderItem(Model.Order currentOrder, int productId)
{
foreach (var orderItem in currentOrder.OrderItems)
{
if (orderItem.Product.Id == productId)
{
currentOrder.OrderItems.Remove(orderItem);
}
}
}
异常详细信息:System.InvalidOperationException :集合已修改;枚举操作可能不会执行
Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute
推荐答案
修改循环不会在里面工作的集合。要解决这个问题,列表
有几个方法,使一个集合的一批的修改。你的情况,使用:
Modifying a collection inside a loop doesn’t work. To work around that, List
has a few methods that allow "batch" modifications of a collection. In your case, use:
currentOrder.OrderItems.RemoveAll(x => x.Product.Id == productId)
这篇关于从一个普通的列表与LT删除项目; T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!