无法从每个循环C#的列表内的列表中删除列表项 [英] Unable to remove list item from list inside a for each loop C#

查看:45
本文介绍了无法从每个循环C#的列表内的列表中删除列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 _interestlist 的自定义对象列表.现在,我要删除此列表中所有将活动"成员设置为false的项目.我写了这样的东西

I have a list of custom objects named _interestlist. Now I want to remove all the items in this list which have "active" member is set to false. and I wrote some thing like this

      int counter = 0;
        foreach (var interest in _interestlist)
        {
            if (interest.active==false)
            {
                _interestlist.Remove(interest);
            }
            counter++;
        }

但这会引发这样的错误

Collection was modified; enumeration operation may not execute.

通过循环是否可以执行此操作?还有其他方法可以实现这一目标吗?

Isn't this operation possible through a loop? IS there any other way to achieve this?

推荐答案

如上所述,一个foreach循环使用枚举器枚举您的列表,该列表在迭代时无法修改.

As stated above, a foreach loop is using an Enumerator to enumerate your list, which cant be modified while iterating.

您可以改用LINQ:

var count  = _interestList.RemoveAll(x => x.active == false);

计数是已删除元素的数量.

Where count is the number of elements removed.

这篇关于无法从每个循环C#的列表内的列表中删除列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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