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..

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.