C# 泛型Dictionary (Hashtable)

來源:互聯網
上載者:User

 

C# 泛型Dictionary (Hashtable)using System;using System.Collections.Generic;public class Example{    public static void Main()    {        //建立泛型雜湊表,然後加入元素        Dictionary<string, string> oscar = new Dictionary<string, string>();        oscar.Add("哈莉•貝瑞", "《死囚之舞》");        oscar.Add("朱迪•丹奇", "《攜手人生》");        oscar.Add("尼科爾•基德曼", "《紅磨坊》");        oscar.Add("詹妮弗•康納利", "《美麗心靈》");        oscar.Add("蕾妮•齊維格", "《BJ單身日記》");        //刪除元素        oscar.Remove("詹妮弗•康納利");        //假如不存在元素則加入元素        if (!oscar.ContainsKey("茜茜•斯派克")) oscar.Add("茜茜•斯派克", "《不倫之戀》");        //顯然容量和元素個數        Console.WriteLine("元素個數: {0}", oscar.Count);        //遍曆集合        Console.WriteLine("74屆奧斯卡最佳女主角及其電影:");        foreach (KeyValuePair<string, string> kvp in oscar)        {            Console.WriteLine("姓名:{0},電影:{1}", kvp.Key, kvp.Value);        }        //得到雜湊表中鍵的集合        Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;        //遍曆鍵的集合        Console.WriteLine("最佳女主角:");        foreach (string s in keyColl)        {            Console.WriteLine(s);        }        //得到雜湊表值的集合        Dictionary<string, string>.ValueCollection valueColl = oscar.Values;        //遍曆值的集合        Console.WriteLine("最佳女主角電影:");        foreach (string s in valueColl)        {            Console.WriteLine(s);        }        //使用TryGetValue方法擷取指定鍵對應的值        string slove = string.Empty;        if (oscar.TryGetValue("朱迪•丹奇", out slove))            Console.WriteLine("我最喜歡朱迪•丹奇的電影{0}", slove);        else            Console.WriteLine("沒找到朱迪•丹奇的電影");        //清空雜湊表        oscar.Clear();        Console.ReadLine();    }}運行效果如下:

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.