The SortedDictionary itself doesn’t support backward iteration, but you have several possibilities to achieve the same effect.
-
Use
.Reverse
-Method (Linq). (This will have to pre-compute the whole dictionary output but is the simplest solution)var Rand = new Random(); var Dict = new SortedDictionary<int, string>(); for (int i = 1; i <= 10; ++i) { var newItem = Rand.Next(1, 100); Dict.Add(newItem, (newItem * newItem).ToString()); } foreach (var x in Dict.Reverse()) { Console.WriteLine("{0} -> {1}", x.Key, x.Value); }
-
Make the dictionary sort in descending order.
class DescendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return y.CompareTo(x); } } // ... var Dict = new SortedDictionary<int, string>(new DescendingComparer<int>());
-
Use
SortedList<TKey, TValue>
instead. The performance is not as good as the dictionary’s (O(n) instead of O(logn)), but you have random-access at the elements like in arrays. When you use the generic IDictionary-Interface, you won’t have to change the rest of your code.
Edit :: Iterating on SortedLists
You just access the elements by index!
var Rand = new Random();
var Dict = new SortedList<int, string>();
for (int i = 1; i <= 10; ++i) {
var newItem = Rand.Next(1, 100);
Dict.Add(newItem, (newItem * newItem).ToString());
}
// Reverse for loop (forr + tab)
for (int i = Dict.Count - 1; i >= 0; --i) {
Console.WriteLine("{0} -> {1}", Dict.Keys[i], Dict.Values[i]);
}