Dictionary基本應用

來源:互聯網
上載者:User

protected void Page_Load(object sender, EventArgs e)
    {
        IList<string> AList = new List<string>();
        AList.Add("KimhillZhangA");
        AList.Add("KimhillZhangB");
        AList.Add("KimhillZhangC");

        IList<string> BList = new List<string>();
        BList.Add("KimhillZhangD");
        BList.Add("KimhillZhangE");
        BList.Add("KimhillZhangF");

        Dictionary<string, IList<string>> dictionary = new Dictionary<string, IList<string>>();
        //添加鍵/值,方法一
        dictionary.Add("A", AList);
        //添加鍵/值,方法二
        dictionary["B"] = BList;

        //遍曆鍵
        foreach (string key in dictionary.Keys)
        {
            //遍曆某鍵的值
            foreach (string val in dictionary[key])
            {
               
            }
        }

        //取某鍵的值,,使用 TryGetValue 方法作為一種更有效方法來檢索值
        if (dictionary.TryGetValue("A", out AList))
        {
            for (int i = 0; i < AList.Count; i++)
            {
                Response.Write(AList[i]);
            }
        }
        //是否包含某鍵
        if (!dictionary.ContainsKey("A"))
        {
            dictionary.Add("A", AList);
        }

        //由於基於 IDictionary 的集合中的每個元素都是一個鍵/值對,因此元素類型既不是鍵的類型,也不是值的類型。而是 KeyValuePair 類型
        foreach (KeyValuePair<string, IList<string>> kvp in dictionary)
        {
            string key = kvp.Key;//key包含了兩個鍵,A,B
            for (int i = 0; i < kvp.Value.Count; i++)
            {
                Response.Write(kvp.Value[i]);
            }
        }

       //定義一個<string,int>的Dictionary,讓它的值進行添加

      Dictionary<string,int> dic = new Dictionary<string,int>();

    //添加兩個鍵為"成績1","成績2";並為它們的值賦為0

     dic["成績1"] = 0;

     dic["成績2"] = 0;

   // 把這兩個值分別加1

     dic["成績1"]++;

     dic["成績2"]++;

    }

聯繫我們

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