I'm trying to find an elegant way to iterate over a list while items are removed at the same time.
I know this solution. But my conditions are something harder:
- all single-threaded here
- Iteration must be forward.
- Every item must be processed exactly once.
- Multiple and random items can be removed while 1 item is being processed.
- Items are complex and smart objects. They execute a custom method and it can decide that some items (0 to all) shall be removed.
- (add and insert can happen too, but just now this is not important, in case there is a way to handle this at the same time, that would be great)
Question: Is this possible ? If yes, how ?
I have the idea of marking the objects as removed / inactive. When I iterate again later, I will remove them without calling them to do things. The iteration will be repeated quite often, that's why every object must have exactly 1 turn at each iteration. Would that work ?
This is how I handle things now. It's not perfect but gives you the hint what is asked I hope.
Pseudo-code:
class Foo
{
public void DoStuff()
{
// do other stuff
if (condition)
Kill(x); // should result in list.RemoveAt(x) somehow
}
}
class Program
{
[STAThread]
static void Main(string[] args)
{
List<Foo> list = new List<Foo>();
for (int i = 0; i < 15; i++)
list.Add(new Foo());
for (int i = 0; i < list.Count; i++)
list[i].DoStuff();
Console.ReadKey();
}
}
(This is not an XY Problem. I'm sure. I have this sitting on my mind for years now and I decided to finally find a solid solution. I'm working in C# for this. This is not a prank. I'm sorry if it seams like it.)
Thanks for any help!