Home > Software design >  Delete the current element in an array
Delete the current element in an array

Time:09-13

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
    }
}

CodePudding user response:

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();

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Whenever you want to delete entries from a collection, you should never loop through that collection from beginning to end, but always from end back to beginning.

By the way, C# does not allow you deleting entries from a collection while looping through that collection using a foreach loop.

  • Related