views:

104

answers:

3

Hi,

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.

+12  A: 

Stop!

Dictionaries and hashtables and sets have no ordering.

There is absolutely no point in sorting or changing the order.

leppie
Hahahahha +1 for **stop**. xD
Cipi
This answer is funny, but @tvanfossons's is more informative.
Vinko Vrsalovic
@Vinko Vrsalovic: There is nothing funny about my answer. I am dead f*cking serious.
leppie
thanks leppie, but the answer from tvanfosson is just what i was after.thanks again.
StarCub
@leppie: You being serious doesn't stop this answer from being funny
Vinko Vrsalovic
+1  A: 

If you want dictionaries to have a certain order, you should look into SortedDictionary. See this article.

Dlaor
+8  A: 

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.

tvanfosson