How to add items to a collection while consuming it?

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

    You can probably also create a recursive function, like this (untested):

    IEnumerable GetUrl(string url)
    {
      foreach(string u in GetUrl(url))
        yield return u;
      foreach(string ret_url in WHERE_I_GET_MY_URLS)
        yield return ret_url;
    }
    
    List MyEnumerateFunction()
    {
      return new List(GetUrl("http://www.google.com"));
    }
    

    In this case, you will not have to create two lists, since GetUrl does all the work.

    But I may have missed the point of you program.

提交回复
热议问题