Add elements to a list while iterating over it

你说的曾经没有我的故事 提交于 2019-12-11 05:56:35

问题


I'm trying to add new elements to a list of lists while iterating over it

List<List<String>> sets = new List<List<string>>();

foreach (List<String> list in sets)
{
      foreach (String c in X)
      {
          List<String> newSet = ir_a(list, c, productions);

          if (newSet.Count > 0)
          {
              sets.Add(newSet);
          }
      }
}

The error I get after a few loops is this:

Collection was modified; enumeration operation may not execute

I know the error is caused by modifying the list, so my question is: What's the best or most fancy way to sort this thing out?

Thanks


回答1:


You might get away with this in other languages but not C#. They do this to avoid funny runtime behaviour that isn't obvious. I prefer to set up a new list of things you are going to add, populate it, and then insert it after the loop.

public class IntDoubler
{
    List<int> ints;

    public void DoubleUp()
    {
        //list to store elements to be added
        List<int> inserts = new List<int>();

        //foreach int, add one twice as large
        foreach (var insert in ints)
        {
            inserts.Add(insert*2);
        }
        //attach the new list to the end of the old one
        ints.AddRange(inserts);
    }
}

Imagine that if you had a foreach loop, and you added an element to it each time, then it would never end!

Hope this helps.



来源:https://stackoverflow.com/questions/44148291/add-elements-to-a-list-while-iterating-over-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!