迭代过程中的exception收集和从该集合中删除项目

我在foreach循环中从ArrayList中删除项目并获得以下exception。

collections被修改; 枚举操作可能无法执行。

如何删除foreach中的项目,

编辑: 可能有一个项目要删除或两个或全部。

以下是我的代码:

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

编辑:你还可以建议代码。 我是否需要将其分解为小方法和exception处理等。

无效的参数exception从ArrayList创建通用列表

 foreach (var fullFilePath in new List(attachmentsFilePath)) 

{

alt text http://img641.imageshack.us/img641/1628/invalidargument1.png

当我使用List ,exception是Argument’1’:无法从’System.Collections.ArrayList’转换为’int’

attachmentsFilePath声明如下

 ArrayList attachmentsFilePath = new ArrayList(); 

但当我宣布这样时,问题就解决了

 List attachmentsFilePath = new List(); 

您可以迭代集合的副本:

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

另一种方法,从最后开始并删除你想要的方法:

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

迭代时,您无法从集合中删除项目。

您可以找到需要删除的项目的索引,并在迭代完成后将其删除。

 int indexToRemove = 0; // Iteration start if (fileName.Equals(names[i].Trim())) { indexToRemove = i; break; } // End of iteration attachmentsFilePath.RemoveAt(indexToRemove); 

但是,如果您需要删除多个项目,请迭代列表的副本:

 foreach(string fullFilePath in new List(attachmentsFilePath)) { // check and remove from _original_ list } 
  List names = new List() { "Jon", "Eric", "Me", "AnotherOne" }; List list = new List() { "Person1", "Paerson2","Eric"}; list.RemoveAll(x => !names.Any(y => y == x)); list.ForEach(Console.WriteLine); 

枚举(或使用foreach)时,您无法修改该集合。 如果您确实要删除项目,则可以标记它们,然后使用其Remove方法将其从列表中删除

请执行下列操作:

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

这样您就可以创建原始列表的副本以进行迭代

您可以遍历集合以查看需要删除的项目,并将这些索引存储在单独的集合中。 最后,您需要以相反的顺序遍历要删除的索引,并从原始集合中删除每个索引。

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