How to add items to a collection while consuming it?

后端 未结 11 556
离开以前
离开以前 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 12:55

    I assume you want to iterate over the whole list, and each item you add to it? If so I would suggest recursion:

    var urls = new List();
    var turls = new List u)
    {
        foreach(string url in u)
        {
            List newUrls = GetLinks(url);
    
            urls.AddRange(newUrls);
    
            iterate(newUrls);
        }
    }
    

提交回复
热议问题