Hi guys,
How to sort hashtable keys in ascending order.
I have 5 keys 1,2,3,4,5 and respective values are 10,7,8,6,9,5.

but when i am displaying records it shows like this.....

foreach (DictionaryEntry entry in srque)
 {
     MessageBox.Show("Key === " +entry.Key);
     MessageBox.Show("Value ===" +entry.Value);
 }

the output i am getting like
Key=== 4 and value === 9
Key=== 2 and value === 7
Key=== 5 and value === 5
Key=== 1 and value === 10
Key=== 3 and value === 8

How to get output like
Key=== 1 and value === 10
Key=== 2 and value === 7
Key=== 3 and value === 8
Key=== 4 and value === 9
Key=== 5 and value === 5

when i am adding keys and values in hastable inserting it with sorting i.e ascending order.

Thanks in advance..

Dani AI

Generated

is right: Hashtable (and Dictionary) do not preserve insertion or sort order, so a foreach will appear random. For UI, you either sort at bind time or switch to a sorted collection so enumeration is always ascending.

If you must keep a Hashtable and you are filling an ASP.NET DropDownList, sort the keys when binding. Use numeric ordering (not string) so that 10 does not come before 2. This works with your existing srque:

// using System.Linq;
DropDownList1.DataSource = srque
    .Cast<System.Collections.DictionaryEntry>()
    .OrderBy(de => Convert.ToInt32(de.Key));   // numeric sort

DropDownList1.DataTextField = "Value";  // what users see
DropDownList1.DataValueField = "Key";   // the submitted value
DropDownList1.DataBind();

If you want the data structure itself to be kept in ascending key order (no per-bind sorting), use a generic SortedDictionary<int,int> or SortedList<int,int> instead of Hashtable. Both enumerate in ascending key order; SortedList is a bit leaner and faster for lookups with fewer inserts, while SortedDictionary scales better with frequent inserts. Example bind:

var map = new SortedDictionary<int,int>();
map[1] = 10; map[2] = 7; map[3] = 8; map[4] = 9; map[5] = 5;

DropDownList1.DataSource = map;         // already sorted by key
DropDownList1.DataTextField = "Value";
DropDownList1.DataValueField = "Key";
DropDownList1.DataBind();

Tip: if your keys are stored as strings, convert them to int before sorting or use OrderBy(k => int.Parse(k)) as ’s LINQ approach suggests conceptually, so you get true numeric order.

Recommended Answers

All 4 Replies

Are you using a HashTable or a Dictionary?

And by their nature, both HashTable and Dictionary are not sorted and don't care what order you enter them. So you need to get the keys, sort them, then get the values for those keys.

Or you could use SortedDictionary.

Actually i am using HashTable , what i want to add the key values to dropdown with asc. order.

The output would be best served sorted (not the actual object).
Here is a sample that shows a sample Hashtable sorted by the value and by the key.
I created it from a Dictionary because it is easier.

 Hashtable hashNames = new Hashtable(new Dictionary<string, string>
 {
    {"Andy", "Zuckerman"},
    {"Zoey", "Anderson"},
    {"Bob", "Yarnell"},
    {"Yolanda", "Brown"}
 });

 List<KeyValuePair<string, string>> lst_kvpByLastName =
 (
    from strKey in hashNames.Keys.OfType<string>()
    let strValue = hashNames[strKey].ToString()
    orderby strValue // <<---
    select new KeyValuePair<string, string>(strKey, strValue)
 ).ToList();

 List<KeyValuePair<string, string>> lst_kvpByFirstName =
 (
    from strKey in hashNames.Keys.OfType<string>()
    let strValue = hashNames[strKey].ToString()
    orderby strKey // <<---
    select new KeyValuePair<string, string>(strKey, strValue)
 ).ToList();

Thanks thines01 and Momerath....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.