This is what I studied to see if I can take what was
List<MdiChild> openMdiChildren = new List<MdiChild>(); foreach(child in MdiManager.Pages) { openMdiChildren.Add(child); } foreach(child in openMdiChild) { child.Close(); }
and shorten it so it doesn't take 2 foreach .
Note I changed what are called to simplify this object for this example (they come from third-party controls). But for information and understanding, MdiManager.Pages inherits a CollectionBase form, which in turn inherits IEnumerable
and MdiChild.Close() removes the open child from the MdiManager.Pages collection, thereby modifying the collection and causing the enumeration to throw an exception if the collection was modified during the enumeration, for example.
foreach(child in MdiManage.Pages) { child.Close(); }
I managed to work with double foreach before
((IEnumerable) MdiManager.Pages).Cast<MdiChild>.ToList() .ForEach(new Action<MdiChild>(c => c.Close());
Why doesnβt it have the same problems with changing the collection during enumeration? My best guess is that when enumerating over a list created by ToList, it is invoked that it actually performs actions in the corresponding element in the MdiManager.Pages collection, and not in the generated list.
Edit
I want to make it clear that my question is how I can simplify this, I just wanted to understand why there were no problems with changing the collection when I executed it, as I wrote it now.
source share