使用第一个foreach语句中的元素嵌套一个Foreach语句

时间:2019-05-09 08:49:49

标签: c# xamarin

我正在尝试为堆栈布局嵌套一个foreach语句,以获取其中的每个项目都是堆栈布局,并且堆栈布局还包含要包含一个条目的堆栈布局。

       `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);

        }`

我在foreach (ExpandableEditor Item in Labh)上总是收到错误消息,

  <System.InvalidOperationException: 'Collection was modified; enumeration 
  operation may not execute.'>

2 个答案:

答案 0 :(得分:0)

ForEach将在集合上打开一个迭代器/枚举器。您尝试执行的步骤:

  

l.Children.RemoveAt(0);

     

l.Children.Insert(0,newlabel);

它会发出犯规声音(就像是)。您可以改用For循环。

答案 1 :(得分:0)

发生异常可能是因为这部分:

// 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

您不能在要循环播放的集合中添加或删除内容!

解决此问题的一种方法是在循环之前创建l.Children的副本,然后循环遍历该副本。可以通过ToList完成:

var Labh = l.Children.OfType<ExpandableEditor>().ToList();