从一个普通的列表与LT删除项目; T> [英] removing items from a generic List<t>

查看:132
本文介绍了从一个普通的列表与LT删除项目; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的方法,我想删除从我的收藏相匹配的产品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>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆