Marcelo C Fernandes Marcelo C Fernandes - 3 months ago 8
C# Question

How update a list in a foreach

I have a foreach of a List and i want to Update the list or (i donĀ“t know wich is better) create a new one with the new values. How to do this ?
My code is bigger than this because i am decrypting, but if help me with this simple, will fix the other.

foreach (Envolvido envolvido in ListaDados.ItemsSource)
{
for (int i = 0; i < ListaDados.ItemsSource.OfType<object>().Count(); i++)
{
var suspid = Convert.FromBase64String(envolvido.SUSPID);
var ivnome = Convert.FromBase64String(envolvido.IVNOME);
}
}


So, with the help of all, i got the correct answer !

List<Envolvido> mylist = t.Result;
for (int index = 0; index < mylist.Count(); index++)
{
var items = mylist.ToList();
Envolvido envolvido = items[index];

envolvido.SUSPID= Convert.FromBase64String(envolvido.SUSPID);
envolvido.IVNOME = Convert.FromBase64String(envolvido.IVNOME);
}


THANKS!

Answer

Use for for modifing lists. NOT foreach.

As it says on MSDN:

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

        List<Envolvido> mylist = t.Result;

         for (int index = 0; index < mylist.Count(); index++)
         {
             var items = mylist.ToList();
             Envolvido envolvido = items[index];

             envolvido.SUSPID= Convert.FromBase64String(envolvido.SUSPID);
             envolvido.IVNOME = Convert.FromBase64String(envolvido.IVNOME);
          }
Comments