There are times in life when you’d like to have your cake and eat it too. With a hashtable, this means there are times when you want to use the keys to look things up, or iterate in a foreach using DictionaryEntry objects. There are other times though when it would be easiest to treat the collection as if it were an array, using a traditional for(int i=0; … type syntax.
The OrderedDictionary is what lets you have the best of both worlds. Using it, you can perform specific actions at a numeric index in the collection, or you can use the Dictionary Entry style of looping over the collection. Like the other specialized dictionaries I’ve mentioned in the latter part of this week, you will need a using System.Collections.Specialized reference.
Let’s take a look at an example.
OrderedDictionary myOD = new OrderedDictionary();
// Reference the values array style
for (int i = 0; i < myOD.Count; i++)
// Create a strongly typed variable to hold the
// generic object in myOD, then do a cast
string valueString = (string) myOD[i];
// Reference the values Dictionary style
foreach(DictionaryEntry myDE in myOD)
Above you can see I used two different methods to iterate over my collection. In the first example, I used a for loop and a numeric index to retrieve each object (in this case a string) stored in the collection. Using a cast I convert it from the generic object type into a more strongly typed variable.
While it’s true I simply could have used Console.WriteLine(myOD[i].ToString()), you will not always be dealing with string data in your value. This example demonstrates how to do a simple conversion.
In the second loop, you can see code similar to what has been shown all week, using a DictionaryEntry object to iterate over the collection.
The other advantage to an OrderedDictionary is speed. When going over a large collection, reading the OrderedDictionary using the first example, the numeric index, is always going to be faster than using the dictionary style method.
When you need both the power of a collection, and the simple access of a numeric index, the OrderedDictionary is the collection of choice.