0

I am creating a console application game. The game contains Point object (x and y properties) and GameObject which other classes inherit from.

I create a dictionary:

Dictionary<Point, List<GameObject>> myDict

Each point in the dictionary stores list with object / objects. I don't wanna empty points. An example for initializing dictionary:

1. <(0,0), List<obj1>>
2. <(35,10), List<obj2, obj3>>
3. <(8,9), List<obj4, obj5>>
4. <(40,3), List<obj6>>

If obj1 moves to (0,1):

<(0,1), List<obj1>>
<(35,10), List<obj2, obj3>>
<(8,9), List<obj4, obj5>>
<(40,3), List<obj6>>

As you can see, the pair with the key (0,0) has been removed and (0,1) has been added.

if obj2 moves to (8,9):

<(0,1), List<obj1>>
<(35,10), List<obj3>>
<(8,9), List<obj4, obj5, obj2>>
<(40,3), List<obj6>>

In this case, obj2 has just been removed from the list and the key wasn't removed because it stores obj3 and it's not empty. obj3 was added to (8,9) list.

These manipulations will be done every 250 milliseconds, inside the game loop, automatically. I tried to use foreach loop, something like that:

foreach (KeyValuePair<Point, List<GameObject>> kvp in myDict)
{
        foreach (GameObject obj in kvp.Value) {
                obj.move();
        }
}

But it doesn't work because as I understood I cannot add / remove keys when I iterate.

Do you have any suggestions?

Some important thing:

  • I have to use dictionary for that.
  • GameObject don't have Point property. you can know where the GameObject located only if you check in the dictionary. please don't tell me to add this property because I can't and that not the target.
Luis
  • 3,257
  • 13
  • 50
  • 59
  • this solution seems best http://stackoverflow.com/questions/9892790/deleting-while-iterating-over-a-dictionary – Jonesopolis Jul 03 '13 at 17:42
  • You can't change or remove the keys in the context of an enumerator but nothing prevents you from getting all `KeyValuePair` to an array and then manipulating that.. I know you said you _have_ to use a Dictionary, but it's not the right structure for what you want. – Simon Belanger Jul 03 '13 at 17:42
  • Your restriction on not adding the `Point` property to the `GameObject` seems very arbitrary. Is there any reason behind it? – Pranav Negandhi Jul 03 '13 at 18:04

2 Answers2

1

If you need to stick with a Dictionary, the easiest way to solve your problem would be to use a temporary Dictionary while you iterate, so you can actually remove/add keys.

As I understand from your foreach loop, every GameObject is going to move, so you could just iterate on your Dictionary and build a new one from scratch with the new values.

Maxime R.C
  • 179
  • 5
0

Questionable design practices aside, this will probably fix your concurrent modifications issue:

foreach (GameObject obj in myDict.SelectMany(pair=>pair.Value).ToList())
{
    obj.move();
}
Mike Asdf
  • 2,309
  • 26
  • 34