How to add items to a collection while consuming it?

后端 未结 11 677
离开以前
离开以前 2021-01-15 12:44

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

var urls         


        
11条回答
  •  佛祖请我去吃肉
    2021-01-15 13:08

    You can't, basically. What you really want here is a queue:

    var urls = new Queue();
    urls.Enqueue("http://www.google.com");
    
    while(urls.Count != 0)
    {
        String url = url.Dequeue();
        // Get all links from the url
        List newUrls = GetLinks(url);
        foreach (string newUrl in newUrls)
        {
            queue.Enqueue(newUrl);
        }
    }
    

    It's slightly ugly due to there not being an AddRange method in Queue but I think it's basically what you want.

提交回复
热议问题