The example below throws an InvalidOperationException, ‘Collection was modified; enumeration operation may not execute.’ when executing the code.
var urls = new List<string>(); urls.Add('http://www.google.com'); foreach (string url in urls) { // Get all links from the url List<string> newUrls = GetLinks(url); urls.AddRange(newUrls); // <-- This is really the problematic row, adding values to the collection I'm looping }
How can I rewrite this in a better way? I’m guessing a recursive solution?
You can’t, basically. What you really want here is a queue:
It’s slightly ugly due to there not being an
AddRangemethod inQueue<T>but I think it’s basically what you want.