Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete the current element in an array

How can I delete the current element of an array inside a foreach-loop?

My programm gets data form a DB and sends it to a new one via HTTP requests. Now I want to post a JSON string to my new DB. If it was a success I want to delete the current array item wich im working with. Something like this.

foreach(var item in array)
{
    bool decide = method.DoSomething();
    if(decide == true)
    {
        //delete current item
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

there are 2 ways (both were tested)

foreach (var item in array.ToList())
    {
         bool decide = method.DoSomething();
        if (decide == true)
        {
            item.Remove();
        }
    }

and

for ( i=0; i <  array.Length; i++) 
    {
         bool decide = method.DoSomething();
        if (decide == true)
        {
            array[i].Remove();
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading