How to add items to a collection while consuming it?

后端 未结 11 627
离开以前
离开以前 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条回答
  •  旧时难觅i
    2021-01-15 13:09

    I would create two lists add into the second and then update the reference like this:

    var urls = new List();
    var destUrls = new List(urls);
    urls.Add("http://www.google.com");
    foreach (string url in urls)
    {    
        // Get all links from the url    
        List newUrls = GetLinks(url);    
        destUrls.AddRange(newUrls);
    }
    urls = destUrls;
    

提交回复
热议问题