迭代过程中收集异常并从该集合中删除项目

Kas*_*hif 5 c# c#-3.0 c#-2.0

我在foreach循环中从ArrayList中删除项目并获得以下异常.

收集被修改; 枚举操作可能无法执行.

如何删除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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

foreach (var fullFilePath in new List<string>(attachmentsFilePath))
Run Code Online (Sandbox Code Playgroud)

{

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

当我使用List<ArrayList>异常是Argument'1':无法从'System.Collections.ArrayList'转换为'int'

attachmentsFilePath声明如下

ArrayList attachmentsFilePath = new ArrayList();
Run Code Online (Sandbox Code Playgroud)

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

List<ArrayList> attachmentsFilePath = new List<ArrayList>();
Run Code Online (Sandbox Code Playgroud)

Mik*_*ael 6

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

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


Ode*_*ded 5

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

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

int indexToRemove = 0;

// Iteration start

if (fileName.Equals(names[i].Trim()))
{
    indexToRemove = i;
    break;
}

// End of iteration

attachmentsFilePath.RemoveAt(indexToRemove);
Run Code Online (Sandbox Code Playgroud)

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

foreach(string fullFilePath in new List<string>(attachmentsFilePath))
{
    // check and remove from _original_ list
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不创建要删除的索引列表? (2认同)
  • 存储索引列表是有风险的.您要么必须反向遍历索引列表,要么每次删除元素时都保持偏移量. (2认同)

jon*_*ten 2

您可以迭代集合的副本:

foreach(var fullFilePath in new ArrayList(attachmentsFilePath))
{
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)