Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-3.0

c#-2.0

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,

EDIT: There might be one item to remove or two or all.

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

EDIT: Can you also advice on code. Do I need to break it into small methods and exception handling etc.

Invalid argument exception On creating generic list from ArrayList

foreach (var fullFilePath in new List<string>(attachmentsFilePath))

{

alt text

When I use List<ArrayList> the exception is Argument '1': cannot convert from 'System.Collections.ArrayList' to 'int'

attachmentsFilePath is declared like this

ArrayList attachmentsFilePath = new ArrayList();

But when I declared it like this, problem solved

List<ArrayList> attachmentsFilePath = new List<ArrayList>();
like image 822
Kashif Avatar asked Mar 30 '10 12:03

Kashif


1 Answers

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);
}
like image 100
Mikael Avatar answered Nov 03 '22 00:11

Mikael