title: Exception during iteration on collection and remove items from that collection
body: <p>I remove item from ArrayList in foreach loop and get follwing exception.</p>
  
  <p><strong>Collection was modified; enumeration operation may not execute.</strong></p>
  
  <p>How can I remove items in foreach, </p>
  
  <p><strong>EDIT:</strong> <strong>There might be one item to remove or two or all.</strong></p>
  
  <p>Following is my code:</p>
  
  <pre><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 &lt; 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;
  }
  </code></pre>
  
  <p><strong>EDIT: Can you also advice on code. Do I need to break it into small methods and exception handling etc.</strong></p>
  
  <p>Invalid argument exception On creating generic list from ArrayList</p>
  
  <pre><code>foreach (var fullFilePath in new List&lt;string&gt;(attachmentsFilePath))
  </code></pre>
  
  <p>{</p>
  
  <p><a href="https://i.stack.imgur.com/x6nTx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x6nTx.png" alt="alt text"></a>
  </p>
  
  <p>When I use <code>List&lt;ArrayList&gt;</code> the exception is 
  Argument '1': cannot convert from 'System.Collections.ArrayList' to 'int'</p>
  
  <p>attachmentsFilePath  is declared like this</p>
  
  <pre><code>ArrayList attachmentsFilePath = new ArrayList();
  </code></pre>
  
  <p>But when I declared it like this, problem solved</p>
  
  <pre><code>List&lt;ArrayList&gt; attachmentsFilePath = new List&lt;ArrayList&gt;();
  </code></pre>