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.
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).
Note that
ReverseKeyCompareris 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.