如何将项目添加到集合,而消费它? [英] How to add items to a collection while consuming it?

查看:94
本文介绍了如何将项目添加到集合,而消费它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的例子引发InvalidOperationException集合已修改;枚举操作可能无法执行。执行code时。

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:

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);
    }
}

这是稍微难看,由于有不是在队列℃的的AddRange 方法; T&GT; ,但我认为它基本上你想要什么。

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

这篇关于如何将项目添加到集合,而消费它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆