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))
{
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>();
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With