hashtable C# 雜湊表

來源:互聯網
上載者:User

一、雜湊表(hashtable)簡述

在.net framework中,hashtable是system.collections命名空間提供的一個容器,用於處理和表現類似key/value的索引值對,其中key通常可用來快速尋找,同時key是區分大小寫;value用於儲存對應於key的值。hashtable中key/value索引值對均為object類型,所以hashtable可以支援任何類型的key/value索引值對.

二、雜湊表的簡單操作

在雜湊表中添加一個key/value索引值對:hashtableobject.add(key,value);
在雜湊表中去除某個key/value索引值對:hashtableobject.remove(key);
從雜湊表中移除所有元素: hashtableobject.clear();
判斷雜湊表是否包含特定鍵key: hashtableobject.contains(key);
下面控制台程式將包含以上所有操作:
using system;
using system.collections; //使用hashtable時,必須引入這個命名空間
class hashtable
{
  public static void main()
  {
   Hashtable ht=new Hashtable();
   ht.Add("a","a");
   ht.Add("b","b");
   ht.Add("c","c");
   ht.Add("e","e");
   ht.Add("d","d");
   foreach(DictionaryEntry de in ht)
   {
    Console.WriteLine(de.Value);
   }
   Console.WriteLine("-----------------------------------");
   string s=(string)ht["a"];
   Console.WriteLine("(string)ht[\"a\"]={0}",s);
   s=ht["a"].ToString();
   Console.WriteLine("ht[\"a\"].ToString()={0}",s);
   Console.WriteLine("-----------------------------------");
   if(ht.ContainsKey("e"))
   {
    Console.WriteLine("Contains the key of \"e\"");
   }  
   ht.Remove("e");
   Console.WriteLine("Remove(\"e\")");
   if(!ht.Contains("e"))
   {
    Console.WriteLine("It does not Contains the key of \"e\"");
   }
   Console.WriteLine("-----------------------------------");
      ht.clear();//移除所有元素
      console.writeline(ht["a"]); //此處將不會有任何輸出
  }
}

三,遍曆雜湊表

遍曆雜湊表需要用到dictionaryentry object,代碼如下:
foreach(dictionaryentry de in ht) //ht為一個hashtable執行個體
{
  console.writeline(de.key);//de.key對應於key/value索引值對key
  console.writeline(de.value);//de.key對應於key/value索引值對value
}

四,對雜湊表進行排序

對雜湊表進行排序在這裡的定義是對key/value索引值對中的key按一定規則重新排列,但是實際上這個定義是不能實現的,因為我們無法直接在hashtable進行對key進行重新排列,如果需要hashtable提供某種規則的輸出,可以採用一種變通的做法:
arraylist akeys=new arraylist(ht.keys); //別忘了匯入system.collections
akeys.sort(); //按字母順序進行排序
foreach(string skey in akeys)
{
  console.write(skey + ":");
  console.writeline(ht[skey]);//排序後輸出
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.