So, I've been struggling with some code for the last couple of weeks. My problem was that I was using a foreach loop in a context where the contents of the loop might change the iteration list.
Because foreach loops do not guarantee the order in which things are done, it's not valid to have the list change halfway though.
My solution – or hack – was to assign each member of the list that matched a certain criterion – the “has abandoned” method – to a second list and then cycle through the second list, deleting items from the first list.
Here's the code:
private List[LESSTHAN]DataUser[GREATERTHAN] tempList;
...
public void tick()
{
...
foreach (DataUser a in computerQueue) {
a.tick(simTick, results);
if (a.hasAbandoned(simTick))
{
tempList.Add(a);
}
}
...
foreach (DataUser d in tempList)
{
computerQueue.Remove(d);
}
As I implied, it seems like a hack to me.
The real problem, I suppose, is that I used C# lists which don't play nicely with foreach in these circumstances.
But I don't want to re-architect the thing, so let's leave well enough alone and go back to working on the program.