tags:

views:

184

answers:

7

I have a class that inherits from a generic dictionary as follows:

Class myClass : System.Collections.Generic.Dictionary<int, Object>

I have added a list of values to this in a particular order, but I now wish to change that order. Is there any way (without removing and re-adding) that I could effectively re-index the values; so change the object at index 1 to now be at index 10 for example? For example, this doesn't work:

myClass[1].Index = 10;
+4  A: 

Dictionaries (or more generally hashtables) do not have indicies. This goes for all languages.

leppie
+10  A: 

Have a look at the SortedDictionary class where you can sort your items by the key.

Normally, you cannot change the index of items in Dictionary because it is against the principle ;-)

rochal
+1  A: 

Take a look at this question. Not a duplicate but I think it fully applies to you. They suggest you have two collections: both a dictionary (for lookups) and a List (for keeping an order that isn't sortable). If these are reference types, then you shouldn't be too concerned about memory usage here since you're only duplicating pointers (unless, of course, you have a bajillion items in here).

Jaxidian
+3  A: 

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.

Taken from MSDN.

Stevo3000
A: 

I have added a list of values to this in a particular order

There is no such thing like particular order for Dictionary. Perhaps you can look at SortedList. It supports indexing for keys and values but adding / removal are O(n) complexity vs O (log N) for SortedDictionary.

Andrei Taptunov
+8  A: 

Dictionaries by themselves don't have an index order. Consider inheriting from the KeyedCollection class instead. It's a merge of a dictionary and an ordinary list, and it's designed to use a member of your items as the key, and have an index order.

Ilia Jerebtsov
+1 - I never knew about this class; I always self coded this behaviour.
Stevo3000
Thanks - this looks like exactly what I need
pm_2
+1  A: 

Dictionary<> is an unordered collection, you'll only get the elements out of it in the order you put them in by accident. You'll need a SortedDictionary<>.

Hans Passant