-3

I need help to understando this isssue... In this code:

listaVideoTemp = listaVideo;
foreach (var itemVideo in listaVideo)
{
  if (itemVideo.ID == id)
  {
   listaVideoTemp.RemoveAt(i);                            

   listaServidorTemp = listaServidor;
                            
   foreach (var itemServidor in listaServidor)
   {
     listaVideoServidorTemp = itemServidor.PropListaVideo;

     foreach (var itemVideoServidor in itemServidor.PropListaVideo)
     {
       if (itemVideoServidor == id)
         listaVideoServidorTemp.RemoveAt(x);
       x++;
     }
    }
   }
   i++;
}

When execute listaVideoServidorTemp.RemoveAt(x); the item from itemServidor.PropListaVideo also is removed. Can anyone help me?

Exception: Collection has been modified; the enumeration operation may not be performed.

Thanks.

NetMage
  • 26,163
  • 3
  • 34
  • 55
  • `listaVideoTemp = listaVideo` does not make a copy, it points both variables to the same reference. – Heretic Monkey Feb 22 '21 at 22:27
  • 1
    You can't modify a collection while you're iterating through it: `listaVideoTemp.RemoveAt(i);` – Rufus L Feb 22 '21 at 22:27
  • Try `listaVideoTemp = listaVideo.ToList();` Note you'll likely want to do `listaVideo = listaVideoTemp;`after the loop. – juharr Feb 22 '21 at 22:28
  • C# generic `List` are [reference types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types) - in other words, after the assigment, `listaVideoServidorTemp` is the __same object__ as `itemServidor.PropListaVideo` and changes to one effect the other. If you wanted a copy, you needed to do `listaVideoServidorTemp = new List(itemServidor.propListaVideo);`. This seems like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - are you trying to count something in `x` and `i` the really hard way? – NetMage Feb 22 '21 at 22:30
  • What is the purpose of `listaVideoTemp`? What is the purpose of `listaServidorTemp`? – NetMage Feb 22 '21 at 22:40

1 Answers1

-2

The error is telling you that you can't modify a collection while you're iterating through it. In the following line, listaVideoTemp is a reference to listaVideo, which is the item you're iterating through:

listaVideoTemp.RemoveAt(i);

One way to resolve this would be to create a copy of the list instead:

var listaVideoTemp = listaVideo.ToList();
Rufus L
  • 36,127
  • 5
  • 30
  • 43