Three methods of Hashtable sort by key or value in C#

Lionsure 2020-07-07 Original by the website

Hashtable is good for fast searching by key, but it does not provide a sorting method, so its sort needs to be achieved by borrowing an array or other collection. Before discussing the specific methods, first explain the namespace where the Hashtable is located and create a new Hashtable and add some values.

The namespace where the Hashtable is located is: System.Collections, so don't forget to use System.Collections; create a new Hashtable and add three values, as follows:

Hashtable ht = new Hashtable();

ht.Add("a", 5);
       ht.Add("b", 22);
       ht.Add("c", 16);

 

1. Hashtable sort with ArrayList

ArrayList al = new ArrayList(ht.Keys);
       al.Sort();

 

1) Output by key in ascending order

for(int i = 0; i < al.Count; i++)
              Response.Write("Key: " + al[i] + "'s value is: " + ht[al[i]].ToString() + "<br />");

 

Output result:

Key: a's value is: 5

Key: b's value is: 22

Key: c's value is: 16

 

2) Output by key in descending order

for(int i = al.Count - 1; i >= 0; i--)
              Response.Write("Key: " + al[i] + "'s value is: " + ht[al[i]].ToStrings() + "<br />");

 

Output result:

Key: c's value is: 16

Key: b's value is: 22

Key: a's value is: 5

 

 

2. C# sort Hashtable by value with Array

string[] arrKey = new string[ht.Count];//Temporary Hashtable key
       int[] arrValue = new int[ht.Count];//Temporary Hashtable value

ht.Keys.CopyTo(arrKey, 0);
       ht.Values.CopyTo(arrValue, 0);

Array.Sort(arrValue, arrKey);//Sort by HashTable value
       for(int i = 0; i < arrKey.Length; i++)
              Response.Write("Key: " + arrKey[i].ToString() + "'s value is: " + arrValue[i].ToString() + "<br />");

 

Output result:

Key: a's value is: 5

Key: c's value is: 16

Key: b's value is: 22

 

 

3. C# sort Hashtable by key or value with DataTable

DataTable dt = new DataTable();
       dt.Columns.Add("htKey", typeof(string));
       dt.Columns.Add("htValue", typeof(int));

IDictionaryEnumerator ide = ht.GetEnumerator();
       while (ide.MoveNext())
       {
              DataRow dr = dt.NewRow();
              dr["htKey"] = ide.Key.ToString();
              dr["htValue"] = ide.Value.ToString();
              dt.Rows.Add(dr);
       }

DataView dv = dt.DefaultView;
       dv.Sort = "htValue Desc";//This is sorted by value in descending order
       DataTable dt1 = dv.ToTable();

for (int i = 0; i < dt1.Rows.Count; i++)
              Response.Write("Key: " + dt1.Rows[i]["htKey"].ToString() + "'s value is: " + dt1.Rows[i]["htValue"].ToString() + "<br/>");

 

Output result:

Key: b's value is: 22

Key: c's value is: 16

Key: a's value is: 5