Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the current element in an array

Tags:

c#

.net-6.0

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

My program 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 which I'm working with. Something like this.

foreach(var item in array)
{
    bool decide = method.DoSomething();
    if(decide == true)
    {
        //delete current item
    }
}
like image 923
Steven Tumler Avatar asked Sep 13 '26 07:09

Steven Tumler


2 Answers

since you cannot delete items from an array and change the size of it here is a loop approach using a second collection

List<itemClass> keepCollection = new List<itemClass>();

foreach(var item in array)
{
    bool decide = method.DoSomething();
    if(decide == false)
    {
        keepCollection.Add(item);
    }
}

If you need it again in array form just call ToArray()

var finalResult = keepCollection.ToArray();
like image 129
Mong Zhu Avatar answered Sep 16 '26 19:09

Mong Zhu


appraoch with Linq which creates a new array with valid elements and overwrites the existing array

array = array.Where(x => !method.DoSomething(x)).ToArray(); //select valid elements
like image 43
fubo Avatar answered Sep 16 '26 20:09

fubo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!