迭代时将元素添加到列表中

Cod*_*ack 1 c# enumeration exception

我正在尝试将新元素添加到列表列表中,同时迭代它

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);
          }
      }
}
Run Code Online (Sandbox Code Playgroud)

我在几个循环之后得到的错误是这样的:

Collection was modified; enumeration operation may not execute
Run Code Online (Sandbox Code Playgroud)

我知道错误是由修改列表引起的,所以我的问题是:将这个东西排序的最佳或最奇特的方法是什么?

谢谢

pse*_*dul 6

您可能会在其他语言中使用它而不是C#.他们这样做是为了避免不明显的有趣的运行时行为.我更喜欢设置一个新的列表,列出要添加的内容,填充它,然后在循环后插入它.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

想象一下,如果你有一个foreach循环,并且每次都为它添加了一个元素,那么它永远不会结束!

希望这可以帮助.