tags:

views:

187

answers:

6

hi there i am writing a program in C# i have a code like this

Hashtable ht = new Hashtable();
            ht.Add("1", "One");
            ht.Add("2", "Two");
            ht.Add("3", "Three");
            ht.Add("4", "Four");

but Compiler sort it i wanna know how can i prevent sorting hashtable please help me

+1  A: 

What do you mean by the compiler sorting it? There is definitely NO sorting done. How are you looping over the items?

I think that order of items when you loop over the keys isn't guaranteed ->

foreach(object key in hashtable.Keys){
...
}

but from your question I think you'd like to retrieve the items in the exact same order as you have inserted them - maybe the best solution would be to keep parallel List of your keys; and retrieve keys for looping over hashtable from there.

Axarydax
hii wanna show it like when i add it to hashtable like this ===> one two three frour but its not like this
Mehdi
@user222820: If you want a data structure which preserves insertion order, then don't use Hashtable - it's as simple as that.
Jon Skeet
A: 

When doing:

        Hashtable ht = new Hashtable();
        ht.Add("1", "One");
        ht.Add("2", "Two");
        ht.Add("3", "Three");
        ht.Add("4", "Four");

        foreach (var k in ht.Keys)
        {
            Console.WriteLine(k);
        }

I see no sorting of any kind taking place.

klausbyskov
its not sort . but is it same order that i inserted?
Mehdi
The order I get is 4, 1, 2, 3. Perhaps Hashtable stores its data by hashvalue (hence the name)?
Webleeuw
A: 

Hashtables do not preserve the order of inserted items. They are stored in a data structure that has no concept of a "correct" order. You should assume that items in a hashtable will be stored in a random order.

You should use a List or other structure instead of a Hashtable if the order of the items is important.

Ant
+3  A: 

A HashTable doesn't do sorting as such. It does rearrange the items based on their hash code, so the original order isn't preserved.

If you want to preserve the original order, or want to specify a sort order, you can't use a HashTable only.

To specify a different sort order, you can use a SortedDictionary<T>. To preserve the original order, you can add the items both to a Dictionary<T> and a List<T>.

Guffa
+1  A: 

Use a Dictionary<int, string> or Dictionary <string, string> instead.

Webleeuw
A: 

Try this:

    Hashtable ht = new Hashtable();
    ht.Add("1", "One");
    ht.Add("2", "Two");
    ht.Add("3", "Three");
    ht.Add("4", "Four");

    foreach (var k in ht.Keys.sort)
    {
        Console.WriteLine(k);
    }

Notice the sort after ht.Keys

egarcia