Reputation: 4341
I'm trying to reverse items in a dictionary in C#. I have tried:
Dictionary<double, int> dict = new Dictionary<double, int>();
...add itmes to it....
var v = dict.Reverse()
However, dict.Reverse() gives me a type of IEnumberable>. I was just wondering how I could make it to a type of Dictionary?
Thanks in advance.
Upvotes: 3
Views: 9277
Reputation: 532435
A Dictionary isn't an ordered data structure. For Reverse to have any real meaning you'll need to use a SortedDictionary. You can get a reversed copy of a SortedDictionary by creating a new one with a Comparer that does the opposite sorting to the original (see constructor).
var reversed = new SortedDictionary( original, new ReverseKeyComparer() );
Note that ReverseKeyComparer
is a ficticious class for the example.
Also - you need to know that the SortedDictionary is somewhat of a misnomer, if you equate Dictionary to map or hashtable. It uses a binary tree implementation (Red-Black, I think) with different algorithmic complexity than the hashtable implementation of Dictionary. See the Remarks sections of their respective documentation pages. If performance is critical, you might want to consider whether the ordering is truly important.
Upvotes: 12
Reputation: 3020
If you want dictionaries to have a certain order, you should look into SortedDictionary. See this article.
Upvotes: 3
Reputation: 117220
Stop!
Dictionaries and hashtables and sets have no ordering.
There is absolutely no point in sorting or changing the order.
Upvotes: 15