1. 程式人生 > 其它 >C#中的List、Dictionary、Hashtable

C#中的List、Dictionary、Hashtable

技術標籤:C#

開發工具與關鍵技術:Visual Studio2017
撰寫時間:2020年12月18日

因為最近在複習 然後自己做了點筆記 有什麼不對的可以在下方評論指出

List的特點:是可以快速在集合的任何位置增加或刪除元素,但不支援隨機存取

Eg:將一個數組中的奇數放到一個集合中,再將偶數放到另一個集合中。最終將兩個集合合併為一個集合,並且將奇數顯示在左邊 偶數顯示在右邊

           #region
            將一個數組中的奇數放到一個集合中,再將偶數放到另一個集合中
            最終將兩個集合合併為一個集合,並且將奇數顯示在左邊 偶數顯示在右邊

            int
[] ss = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<int> listqi = new List<int>();//List泛型集合 List<int> listou = new List<int>(); for (int i = 0; i < ss.Length; i++) { if (ss[i] % 2 == 0) { listou.
Add(ss[i]); } else { listqi.Add(ss[i]); } } foreach (var item in listqi) { Console.Write(item + " "); } foreach (var item in listou)
{ Console.Write(item + " "); } Console.ReadKey(); #endregion

在這裡插入圖片描述

Dictionary 類是任何可將鍵對映到相應值的類(如 Hashtable)的抽象父類。

        #region
        Eg:統計每個字元出現的次數 不考慮大小寫
        string str = "送你一朵小紅花小紅花";
        //char:字母  int:次數
        Dictionary<char, int> dic = new Dictionary<char, int>();//字典集合
        for (int i = 0; i < str.Length; i++)
        {
            //如果Dic已經包含了當前迴圈到的這個鍵
            if (dic.ContainsKey(str[i]))
            {
                //值再加
                dic[str[i]]++;

            }
            else
            {
                dic[str[i]] = 1;
            }
        }
        foreach (KeyValuePair<char, int> kv in dic)
        {
            Console.WriteLine("字串  {0}  出現了  {1}  次", kv.Key, kv.Value);
        }
        Console.ReadKey();
        #endregion

在這裡插入圖片描述

Hashtable:類實現一個雜湊表,該雜湊表將鍵對映到相應的值。任何非null物件都可以用作鍵或值。

Eg:在Hashtable中新增資料並輸出

Hashtable ht = new Hashtable();
            ht.Add(1, "送");
            ht.Add(2, "你");
            ht.Add(3, "一");
            ht.Add(4, "朵");
            ht.Add(5, "小");
            ht.Add(6, "紅");
            ht.Add(7, "花");
            foreach (var item in ht.Keys)
            {
                Console.Write(ht[item]);
            }
            Console.ReadKey();

在這裡插入圖片描述