Exception during iteration on collection and remove items from that collection

Posted by Muhammad Kashif Nadeem on Stack Overflow See other posts from Stack Overflow or by Muhammad Kashif Nadeem
Published on 2010-03-30T12:23:01Z Indexed on 2010/03/30 12:33 UTC
Read the original article Hit count: 445

Filed under:
|

I remove item from ArrayList in foreach loop and get follwing exception.

Collection was modified; enumeration operation may not execute.

How can I remove items in foreach

Following is my code:

/*
 * Need to remove all items from 'attachementsFielPath' which does not exist in names array.
 */

try
{
    string attachmentFileNames = txtAttachment.Text.Trim(); // Textbox having file names.
    string[] names = attachmentFileNames.Split(new char[] { ';' });

    int index = 0;

    // attachmentsFilePath is ArrayList holding full path of fiels user selected at any time.
    foreach (var fullFilePath in attachmentsFilePath)
    {
        bool isNeedToRemove = true;

        // Extract filename from full path.
        string fileName = fullFilePath.ToString().Substring(fullFilePath.ToString().LastIndexOf('\\') + 1);

        for (int i = 0; i < names.Length; i++)
        {
        // If filename found in array then no need to check remaining items.
        if (fileName.Equals(names[i].Trim()))
        {
            isNeedToRemove = false;
            break;
        }
        }

        // If file not found in names array, remove it.
        if (isNeedToRemove)
        {
        attachmentsFilePath.RemoveAt(index);
        isNeedToRemove = true;
        }

        index++;
    }
}
catch (Exception ex)
{
    throw ex;
}

© Stack Overflow or respective owner

Related posts about c#3.0

Related posts about c#