如何在消费时将项目添加到集合中?

Jon*_*oln 2 .net c#

下面的示例抛出InvalidOperationException,"Collection已被修改;枚举操作可能无法执行".执行代码时.

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
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能以更好的方式重写这个?我猜一个递归的解决方案?

Jon*_*eet 5

基本上你不能.你真正想要的是一个队列:

var urls = new Queue<string>();
urls.Enqueue("http://www.google.com");

while(urls.Count != 0)
{
    String url = url.Dequeue();
    // Get all links from the url
    List<string> newUrls = GetLinks(url);
    foreach (string newUrl in newUrls)
    {
        queue.Enqueue(newUrl);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于没有AddRange方法,它有点难看,Queue<T>但我认为它基本上是你想要的.