close gaps in dictionary

Hi,

Is it possible that if you delete a dictionary entry, all subsequent entries move up?

I have 4 entrys in my dictionary, for every player who wants to join a local match. So if player 2 leaves the match, player 3 should get the new player 2 etc.
It’s an <int, string> dictionary, the “int” for the position and the “string” for the player name.

Any ideas or better alternatives?

Greetings
J.

Well…List already work this way. You can retrieve player 1 for example by accessing index 0. If player 1 leaves, the player at index 1 (player 2) is now at index 0.

Dictionary.Remove() does that already. If you use .Remove() on an entry then it literally removes it and the indexes shift.

Typically this shouldn’t matter, as you should be searching dictionaries by KVP and not index.

In his case, he’s using the key as the player position, so deleting the 1 key will not modify the key for the other values in the dictionary.
Also, dictionary collections don’t really have an index that you can count on. An OrderedDictionary would be needed if you want to access by index.

Hmm. I guess I don’t understand what hes trying to accomplish here, then. Shifting all of the keys manually seems like a sketchy thing to do, depending the design and what’s hooked into this data.

I may not understand completely also. I thought he wanted player 3 to become the new player 2, but rereading, maybe you are correct. And he simply doesn’t want an empty entry, which wouldn’t occur with a dictionary when an entry is removed.

At 4 entries, there’s no sweat over the need (performance) of a dictionary vs. a list, in my opinion. :slight_smile:

But for fun, you could imagine that if you had a player leave, you could loop from n to the player count - 1 and remove/re-add to the dictionary.

I’m with @Brathnann , it appears OP expects the key to reflect the ‘index’.

Dictionary’s are unsorted. They are NOT indexed. (there is technically a SortedDictionary that is sorted). A Dictionary doesn’t fill in the gaps, there’s no gaps to fill in, in the first place! (there are technically gaps in the underlying data structure, but they don’t get filled in. The gaps are intentional, and are meaningless to the user. A dict of 3 entries could easily have an underlying array of 11 entries)

Anyways… a int->string dict, where the int is sequential. That’s a List!

Thank you all! A list was what I was looking for (never worked with a list before), I did it wrong and used the “int” in the dictionary as Index.