Trouble with foreach loops

I am working on an auto generating world that consists of Corridors, tCorridors and Rooms (more will be added later). when a corridor gets instantiated in it creates a Junction (GameObject) as its child. the junction sends the message to the script to add it to the temp list. i believe the problem is that i am changing the list whilst the forloop is running. this is the error message “InvalidOperationException: Collection was modified; enumeration operation may not execute.” i have messed with booleans and such trying to make it so that the junction list only becomes the temp list when the foreach loop isnt running but i just get stuck. so im asking if anyone knows how i can change the junction list to temp list when the for loop is not running. thanks.

PS i know the “JunctionList = TempJunctionList;” is in the wrong place. i put it there to show what im doing and that i dont know what im doing xD

using UnityEngine;
using System.Collections.Generic;
using System.Collections;

public class SchoolGen : MonoBehaviour {

public GameObject Corridor;
public GameObject tCorridor;
public GameObject Room;

GameObject CurrentInstantiation;

public List<GameObject> JunctionList = new List<GameObject>();
public List<GameObject> TempJunctionList = new List<GameObject>();

void NewJunction (GameObject Self)
{
    TempJunctionList.Add(Self);
}

void Update ()
{    
    JunctionList = TempJunctionList;

    foreach (GameObject Junction in JunctionList)
    {
        if (Random.Range(1, 4) == 1)
        {
            Instantiate(Corridor, Junction.transform.position, Junction.transform.rotation);
            TempJunctionList.Remove(Junction);
        }
    }
}

}

Setting JunctionList = TempJunctionList just means they refer to the same collection. You haven’t actually duplicated the list.

A more appropriate(and functional) solution would be:

 void Update ()
 {    
     List<GameObject> toDelete = new List<GameObject>((int)(JunctionList.Count * 0.34f));
     foreach (GameObject Junction in JunctionList)
     {
         if (Random.Range(1, 4) == 1)
         {
             Instantiate(Corridor, Junction.transform.position, Junction.transform.rotation);
             toDelete.Add(Junction);
         }
     }
     JunctionList.RemoveAll(obj => toDelete.Contains(obj));
 }

Should this really be in the Update function though…?