Search code examples
c#listasp.net-web-apiitemsource

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 which 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!


Solution

  • 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);
              }