[英]removing items from a generic List<t>
I have the following method, I wish to remove items from my collection that match the product Id. 我有以下方法,我希望从我的集合中删除与产品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);
}
}
}
Exception Details: System.InvalidOperationException: Collection was modified; 异常详细信息:System.InvalidOperationException:Collection已修改; 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. 为了解决这个问题,
List
有一些方法可以对集合进行“批量”修改。 In your case, use: 在您的情况下,使用:
currentOrder.OrderItems.RemoveAll(x => x.Product.Id == productId)
You can't modify a collection while iterating it. 迭代时无法修改集合。 Just use a normal
for
loop instead of a foreach
loop. 只需使用普通
for
循环而不是foreach
循环。
By looping this way you can not remove items because its in collection it keeps the track of the stored items. 通过这种方式循环,您无法删除项目,因为它在集合中保留了存储项目的跟踪。
Easy way to do this : 简单的方法:
authorsList.RemoveAll(x => x.ProductId == productId);
or 要么
authorsList = authorsList.Where(x => x.ProductId!= productId).ToList();
您无法从正在迭代的集合中删除项目,您可以跟踪orderItem,然后在完成循环后将其删除
As you realise you can't remove an item from a collection whilst you are looping over it. 如您所知,在循环播放时,无法从集合中删除项目。 I'm sure someone will be able to provided a neater LINQ solution but the following should get you going initially:
我相信有人能够提供更简洁的LINQ解决方案,但以下内容应该让您最初开始:
public void RemoveOrderItem(Model.Order currentOrder, int productId)
{
var selectedOrderItem = null;
foreach (var orderItem in currentOrder.OrderItems)
{
if (orderItem.Product.Id == productId)
{
selectedOrderItem = orderItem;
break;
}
}
if(selectedOrderItem != null)
currentOrder.OrderItems.Remove(selectedOrderItem);
}
"foreach" provides a "Forward-only read-only" iteration of a collection. “foreach”提供集合的“仅向前只读”迭代。
As a workaround, you can copy the reference to another collection and then iterate on the copied collection and remove the items from the original one. 作为解决方法,您可以将引用复制到另一个集合,然后迭代复制的集合并从原始集合中删除项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.