0

I am trying to nest a foreach statement for a stacklayout, to get each item in it which are stacklayouts, and the stacklayouts also contains stacklayouts which I want to contain an entry.

       `var Lab1 = TotalBodyStackLayout2.Children.OfType<StackLayout>();
        foreach (StackLayout l in Lab1)
        {
            StackLayout newstacklayout = new StackLayout();
            Label EDTL = new Label();
            l.Children.RemoveAt(1);

            var Labh = l.Children.OfType<ExpandableEditor>();
            foreach (ExpandableEditor Item in Labh)
            {
                Label newlabel = new Label();
                newlabel.Text = Item.Text;
                l.Children.RemoveAt(0);
                l.Children.Insert(0, newlabel);
            }
            newstacklayout.Children.Add(l.Children[0]);
            MainstackLayout.Children.Add(newstacklayout);

        }`

I keep getting an error at foreach (ExpandableEditor Item in Labh) which says

  <System.InvalidOperationException: 'Collection was modified; enumeration 
  operation may not execute.'>
ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
LBG
  • 51
  • 2
  • 8
  • Possible duplicate of [How to remove elements from a generic list while iterating over it?](https://stackoverflow.com/questions/1582285/how-to-remove-elements-from-a-generic-list-while-iterating-over-it) – BWA May 09 '19 at 08:57

2 Answers2

0

ForEach will open an Iterator/Enumerator on the Collection. The moment you try to:

l.Children.RemoveAt(0);

l.Children.Insert(0, newlabel);

It will cry foul (like it is). You can use a For loop instead.

Community
  • 1
  • 1
Prateek Shrivastava
  • 1,877
  • 1
  • 10
  • 17
0

The exception occurred likely because this part:

// Labh is actually the same collection as l.Children
// It's just a special enumerator over l.Children that skips everything that's not an ExpandableEditor
var Labh = l.Children.OfType<ExpandableEditor>(); 
foreach (ExpandableEditor Item in Labh) // so here you are essentially looping over l.Children
{
    Label newlabel = new Label();
    newlabel.Text = Item.Text;
    l.Children.RemoveAt(0); // while looping over it, you are removing...
    l.Children.Insert(0, newlabel); // ...and adding stuff to l.Children

You can't add or remove stuff from the collection that you are looping over!

One way to solve this is to create a copy of l.Children before looping over it, and loop over the copy instead. This can be done by ToList:

var Labh = l.Children.OfType<ExpandableEditor>().ToList(); 
Sweeper
  • 213,210
  • 22
  • 193
  • 313