Elimino el elemento de ArrayList en el bucle foreach y obtengo la siguiente excepción.Excepción durante la iteración en la colección y eliminar elementos de esa colección
Se modificó la colección; la operación de enumeración no se puede ejecutar.
¿Cómo puedo eliminar elementos en foreach,
EDIT:Puede haber un elemento para eliminar o dos o todos.
que sigue es mi código:
/*
* 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: ¿Puede usted también consejo sobre código. ¿Es necesario que dividirlo en pequeños métodos y gestión de excepciones, etc.
excepción argumento no válido en la creación de la lista genérica ArrayList
foreach (var fullFilePath in new List<string>(attachmentsFilePath))
{
alt text http://img641.imageshack.us/img641/1628/invalidargument1.png
Cuando utilizo el List<ArrayList>
la excepción es Argumento '1': no se puede convertir de 'System.Collections.ArrayList' a 'int'
attachmentsFilePath se declara como esto
ArrayList attachmentsFilePath = new ArrayList();
Pero cuando lo declaré como este, problema resuelto
List<ArrayList> attachmentsFilePath = new List<ArrayList>();
+1, aunque 'ArrayList' debe reemplazarse con una' Lista 'de tipo apropiado. –
He creado una nueva lista (attachementsFilePath) y me da una excepción arguemnt inválida. He adjuntado iamge en el área de preguntas. –
Kashif