Good morning!
So, I have the following algorithm:
- Iterate through every element of a list
- Check element status
- If "good", do something, if otherwise "bad", remove it from the list.
In my first attempt, I wrote:
This didn't work because with each removal, the list changes size and due to that fact, I eventually got out of bounds (crash!).
As soon as I understood it, I came-up with the following solution:
It works like a charm, but in my view, it's pretty ugly having to use two lists...
How can I improve this code by using only one list?
There must be a really simple way to do it...
So, I have the following algorithm:
- Iterate through every element of a list
- Check element status
- If "good", do something, if otherwise "bad", remove it from the list.
In my first attempt, I wrote:
B4X:
For Each Element As MyCustomClass in ThisList
If Element.isFineThankYou Then Element.Enjoy Else ThisList.RemoveAt(ThisList.IndexOf(Element))
Next
As soon as I understood it, I came-up with the following solution:
B4X:
Dim RemovalList As List
RemovalList.Initialize
For Each Element As MyCustomClass In ThisList
If Element.isFineThankYou Then Element.Enjoy Else RemovalList.Add(Element)
Next
For Each Element As MyCustomClass In RemovalList
ThisList.RemoveAt(ThisList.IndexOf(Element))
Next
RemovalList.Clear
It works like a charm, but in my view, it's pretty ugly having to use two lists...
How can I improve this code by using only one list?
There must be a really simple way to do it...
Last edited: