title: .NET - Remove  from a List<T> within a 'foreach' loop
body: <p>I have code that I <em>want</em> to look like this:</p>
  
  <pre><code>List&lt;Type&gt; Os;
  
  ...
  
  foreach (Type o in Os)
      if (o.cond)
          return;  // Quitting early is important for my case!
      else
          Os.Remove(o);
  
  ... // Other code
  </code></pre>
  
  <p>This doesn't work, because you cannot remove from the list when you are inside a <code>foreach</code> loop over that list:</p>
  
  <p>Is there a common way to solve the problem?</p>
  
  <p>I can switch to a different type if needed.</p>
  
  <p>Option 2:</p>
  
  <pre><code>List&lt;Type&gt; Os;
  
  ...
  
  while (Os.Count != 0)
       if (Os[0].cond)
           return;
       else
           Os.RemoveAt(0);
  
  ... // Other code
  </code></pre>
  
  <p>Ugly, but it should work.</p>