Hashtable排序的幾種方法(C#)
Hashtable 利于用鍵值快速查找,卻沒有提供排序的方法,所以它的排序需要借住數組或其它集合來實現。在討論具體方法之前,先說明 Hashtable 所在的命名空間和新建一個 Hashtable 且添加一些值。
Hashtable所在的命名空間為:System.Collections,所以別忘了先 using System.Collections;;新建一個 Hashtable,且添加三個值,具體如下:
Hashtable ht = new Hashtable();
ht.Add("a", 5);
ht.Add("b", 22);
ht.Add("c", 16);
1、使用 ArrayList 數組排序
ArrayList al = new ArrayList(ht.Keys);
al.Sort();
1)按鍵升序輸出
for(int i = 0; i < al.Count; i++)
Response.Write("鍵:" + al[i] + " 的值為:" + ht[al[i]].ToString() + "<br />");
輸出結果:
鍵:a 的值為:5
鍵:b 的值為:22
鍵:c 的值為:16
2)按鍵降序輸出
for(int i = al.Count - 1; i >= 0; i--)
Response.Write("鍵:" + al[i] + " 的值為:" + ht[al[i]].ToStrings() + "<br />");
輸出結果:
鍵:c 的值為:16
鍵:b 的值為:22
鍵:a 的值為:5
2、使用 Array 數組按值排序
string[] arrKey = new string[ht.Count];//暫存 Hashtable 的鍵
int[] arrValue = new int[ht.Count];//暫存 Hashtable 的值
ht.Keys.CopyTo(arrKey, 0);
ht.Values.CopyTo(arrValue, 0);
Array.Sort(arrValue, arrKey);//按 HashTable 的值排序
for(int i = 0; i < arrKey.Length; i++)
Response.Write("鍵:" + arrKey[i].ToString() + " 的值為:" + arrValue[i].ToString() + "<br />");
輸出結果:
鍵:a 的值為:5
鍵:c 的值為:16
鍵:b 的值為:22
3、使用 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";//此處是按值降序排列
DataTable dt1 = dv.ToTable();
for (int i = 0; i < dt1.Rows.Count; i++)
Response.Write("鍵:" + dt1.Rows[i]["htKey"].ToString() + " 的值為:" + dt1.Rows[i]["htValue"].ToString() + "<br/>");
輸出結果:
鍵:b 的值為:22
鍵:c 的值為:16
鍵:a 的值為:5