Lets say I have a Dictionary object:
Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();
Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A foreach is easy:
foreach (SomeObject object in myDictionary.Values)
{
// Do stuff to object
}
But how can I perform this in reverse?
A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :)
I'd use a SortedList instead of a dictionary. You can still access it by Key, but you can access it by index as well.
SortedList sCol = new SortedList();
sCol.Add("bee", "Some extended string matching bee");
sCol.Add("ay", "value matching ay");
sCol.Add("cee", "Just a standard cee");
// Go through it backwards.
for (int i = sCol.Count - 1; i >=0 ; i--)
Console.WriteLine("sCol[" + i.ToString() + "] = " + sCol.GetByIndex(i));
// Reference By Key
foreach (string i in sCol.Keys)
Console.WriteLine("sCol[" + i + "] = " + sCol[i]);
// Enumerate all values
foreach (string i in sCol.Values)
Console.WriteLine(i);
It's worth noting that a sorted list stores key/value pairs sorted by key only.
If you have .NET 3.5 you can use the .Reverse() extension method on IEnumerables. For example:
foreach (object o in myDictionary.Values.Reverse())
{
// Do stuff to object
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With