Animals is a dictionary class that contains Animal class objects. DictionaryBase implements IDictionaryEnumerator.GetEnumerator() and I have a problem with the way it displays the entries.
In the following code, I assumed it would display the entries in the same order they are added, however, it turns out they are displayed quite differently.
Animals myAnimals = new Animals();
myAnimals.Add("Swordy", new Animal("Swordy"));
myAnimals.Add("Kollie", new Animal("Kollie"));
myAnimals.Add("Charlie", new Animal("Charlie"));
myAnimals.Add("Kilo", new Animal("Kilo"));
myAnimals.Add("Alpha", new Animal("Alpha"));
// Showing all of the entries with a foreach loop
foreach (DictionaryEntry myEntry in myAnimals)
{
Console.WriteLine("Entry named {0}.", ((Animal)myEntry.Value).Name);
}
This code resulted in this output(witch seems random to me):
Entry named Charlie.
Entry named Alpha.
Entry named Swordy.
Entry named Kollie.
Entry named Kilo.
How are the entries sorted? Is there a way to change it?
Dictionary uses hash table to store the objects, so the default sorting is based on GetHashCode method of each key that you insert into the dictionary.
You can sort the dictionary by using LINQ for ex: