Dictionary sequence/sorting issue
Animals is a dictionary class that contains Animal class objects. Dic开发者_JS百科tionaryBase 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?
Use a SortedDictionary.
Dictionary doesn't guarantee any order. The elements are stored in such a way as to maximise lookup performance at the expense of order.
You either need to use a different class (such as SortedList) or sort the values when you come to use them.
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:
myAnimals.OrderBy(e => ((Animal)e.Value).Name)
DictionaryBase
does not maintain the order in which items are added. You need to implement ordering in your derived class
If you are repeating a property in the key look at KeyedCollection
KeyedCollection Class
stringStringCollection is a KeyedCollection
foreach (StringStringO ssO in stringStringCollection.OrderBy(x => x.String1).ThenBy(x => x.String2))
{
Console.WriteLine(string.Format("HashCode {0} String1 {1} String2 {2} ", ssO.GetHashCode(), ssO.String1, ssO.String2));
}
精彩评论