<p>The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code. </p>

<pre><code>var urls = new List&lt;string&gt;();
urls.Add("http://www.google.com");

foreach (string url in urls)
{
    // Get all links from the url
    List&lt;string&gt; newUrls = GetLinks(url);

    urls.AddRange(newUrls); // &lt;-- This is really the problematic row, adding values to the collection I'm looping
}
</code></pre>

<p>How can I rewrite this in a better way? I'm guessing a recursive solution?</p>

I would create two lists add into the second and then update the reference like this:
```
```
var urls = new List<string>();
var destUrls = new List<string>(urls);
urls.Add("http://www.google.com");
foreach (string url in urls)
{    
    // Get all links from the url    
    List<string> newUrls = GetLinks(url);    
    destUrls.AddRange(newUrls);
}
urls = destUrls;
```
```