Gasoline
Gasoline

Reputation: 331

Dictionary sequence/sorting issue

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?

Upvotes: 0

Views: 645

Answers (5)

paparazzo
paparazzo

Reputation: 45096

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));
}

Upvotes: 0

Steve Morgan
Steve Morgan

Reputation: 13091

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.

Upvotes: 2

Dean Chalk
Dean Chalk

Reputation: 20451

DictionaryBase does not maintain the order in which items are added. You need to implement ordering in your derived class

Upvotes: 0

Ankur
Ankur

Reputation: 33637

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)

Upvotes: 1

Polyfun
Polyfun

Reputation: 9639

Use a SortedDictionary.

Upvotes: 2

Related Questions