程序开发 > C# > 正文

Hashtable排序的几种方法(C#)

亮术网 2020-07-07 本网原创

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