How to add items to a collection while consuming it?

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

    There are three strategies you can use.

    1. Copy the List<> to a second collection (list or array - perhaps use ToArray()). Loop through that second collection, adding urls to the first.
    2. Create a second List<>, and loop through your urls List<> adding new values to the second list. Copy those to the original list when done looping.
    3. Use a for loop instead of a foreach loop. Grab your count up front. List should leave things indexed correctly, so it you add things they will go to the end of the list.

    I prefer #3 as it doesn't have any of the overhead associated with #1 or #2. Here is an example:

    var urls = new List();
    urls.Add("http://www.google.com");
    int count = urls.Count;
    
    for (int index = 0; index < count; index++)
    {
        // Get all links from the url
        List newUrls = GetLinks(urls[index]);
    
        urls.AddRange(newUrls);
    }
    

    Edit: The last example (#3) assumes that you don't want to process additional URLs as they are found in the loop. If you do want to process additional URLs as they are found, just use urls.Count in the for loop instead of the local count variable as mentioned by configurator in the comments for this answer.

提交回复
热议问题