How to add items to a collection while consuming it?

后端 未结 11 631
离开以前
离开以前 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:07

    alternately, you could treat the collection as a queue

    IList urls = new List();
    urls.Add("http://www.google.com");
    while (urls.Count > 0)
    {
        string url = urls[0];
        urls.RemoveAt(0);
        // Get all links from the url
        List newUrls = GetLinks(url);
        urls.AddRange(newUrls);
    }
    

提交回复
热议问题