Unable to remove list item from list inside a for each loop C# [duplicate]

自闭症网瘾萝莉.ら 提交于 2021-02-11 17:26:14

问题


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++;
        }

But this throws an error like this

Collection was modified; enumeration operation may not execute.

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


回答1:


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

You can use LINQ instead:

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

Where count is the number of elements removed.




回答2:


That is because the foreach uses the GetEnumerator function. That enumerator will invalidate on changing (adding, removing, etc) the collection.

As suggested, use for instead.




回答3:


The standard approach is to keep track of the items to remove (e.g., in another list), and then after Items has been enumerated, enumerate the removelist, removing each item from Items.




回答4:


You can't modify the collection you are iterating in foreach loop, use the for instead:

for (int counter = _interestlist.Count - 1; i >= 0; counter--)
{
    if (!interest[counter].active)
    {
        _interestlist.Remove(interest[counter]);
    }
}

Also, you shouldn't check your bool field like this:

if (!interest.active)



回答5:


Iterating through a list using foreach statement looks like

IEnumerator enumerator = list.GetEnumerator();

while ( enumerator.MoveNext() )
{
    Console.WriteLine( enumerator.Current );
}

You can observe that you use the same object that you got before iterating that's why you cant modify iterated list elements in foreach statement




回答6:


No You can not modify the Enumerators because they are Read-Only

From MSDN : GetEnumerator()

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Solution : One solution is to iterate the items from the last to first for removing the required items.

Try This:

for (int i= _interestlist.Count-1; i >= 0 ;i--)
{
    if (_interestlist[i].active == false)
    {
        _interestlist.Remove(_interestlist[i]);
    }       
}


来源:https://stackoverflow.com/questions/23309136/unable-to-remove-list-item-from-list-inside-a-for-each-loop-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!