Exception during iteration on collection and remove items from that collection [duplicate]

怎甘沉沦 提交于 2019-11-29 07:27:26

You can iterate over a copy of the collection:

foreach(var fullFilePath in new ArrayList(attachmentsFilePath))
{
    // do stuff
}

Another way of doing it, start from the end and delete the ones you want:

List<int> numbers = new int[] { 1, 2, 3, 4, 5, 6 }.ToList();
for (int i = numbers.Count - 1; i >= 0; i--)
{
    numbers.RemoveAt(i);
}
Oded

You can't remove an item from a collection while iterating over it.

You can find the index of the item that needs to be removed and remove it after iteration has finished.

int indexToRemove = 0;

// Iteration start

if (fileName.Equals(names[i].Trim()))
{
    indexToRemove = i;
    break;
}

// End of iteration

attachmentsFilePath.RemoveAt(indexToRemove);

If, however, you need to remove more than one item, iterate over a copy of the list:

foreach(string fullFilePath in new List<string>(attachmentsFilePath))
{
    // check and remove from _original_ list
}
    List<string> names = new List<string>() { "Jon", "Eric", "Me", "AnotherOne" };
    List<string> list = new List<string>() { "Person1", "Paerson2","Eric"};

    list.RemoveAll(x => !names.Any(y => y == x));
    list.ForEach(Console.WriteLine);

while enumerating (or using foreach) you cannot modify that collection. If you really want to remove items, then you can mark them and later remove them from list using its Remove method

do the following:

foreach (var fullFilePath in new List(attachmentsFilePath))
{

this way you create a copy of the original list to iterate through

You could loop over the collection to see which items need to be delete and store those indexes in a separate collection. Finally you would need to loop over the indexes to be deleted in reverse order and remove each from the original collection.

list<int> itemsToDelete

for(int i = 0; i < items.Count; i++)
{
    if(shouldBeDeleted(items[i]))
    {
        itemsToDelete.Add(i);
    }
}

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