I am trying to remove invalid elements of an JArray while iterating over it. Doing this in a foreach loop obviously doesn't work because it doesn't expect the array to get shorter. So I decided to do use a for loop. I am doing it like this:
// data is my JArray, its elements are JObjects
for (int i = 0; i < data.Count; i++)
{
if (!data[i].HasValues) { // checking if element is empty
data[i].Remove();
i--;
}
}
When I tested this it worked correctly. But I am not sure if it is safe or if I am just lucky. For example, I am not sure if the order of the elements stays the same after removing one element. Or are there any other reasons why this could not work?
I guess the best alternative, if this was incorrect, would be to copy all valid elements to a new array. But that would cause a lot of overhead.