C# Dictionary用法總結

來源:互聯網
上載者:User

C# Dictionary用法總結

1、用法1: 常規用

  增加索引值對之前需要判斷是否存在該鍵,如果已經存在該鍵而且不判斷,將拋出異常。所以這樣每次都要進行判斷,很麻煩,在備忘裡使用了一個擴充方法

        public static void DicSample1()        {            Dictionary<String, String> pList = new Dictionary<String, String>();            try            {                if (pList.ContainsKey("Item1") == false)                {                    pList.Add("Item1", "ZheJiang");                }                if (pList.ContainsKey("Item2")== false)                {                    pList.Add("Item2", "ShangHai");                }                else                {                    pList["Item2"] = "ShangHai";                }                if (pList.ContainsKey("Item3") == false)                {                    pList.Add("Item3", "BeiJiang");                }                            }            catch (System.Exception e)            {                Console.WriteLine("Error: {0}", e.Message);            }                      //判斷是否存在相應的key並顯示            if (pList.ContainsKey("Item1"))            {                Console.WriteLine("Output: " + pList["Item1"]);            }            //遍曆Key            foreach (var key in pList.Keys)            {                Console.WriteLine("Output Key: {0}", key);            }            //遍曆Value            foreach (String value in pList.Values)            {                Console.WriteLine("Output Value: {0}", value);            }            //遍曆Key和Value            foreach (var dic in pList)            {                Console.WriteLine("Output Key : {0}, Value : {1} ", dic.Key, dic.Value);            }        }

  

  2、用法2:Dictionary的Value為一個數組

        /// <summary>        /// Dictionary的Value為一個數組        /// </summary>         public static void DicSample2()         {             Dictionary<String, String[]> dic = new Dictionary<String, String[]>();             String[] ZheJiang =  { "Huzhou", "HangZhou", "TaiZhou" };             String[] ShangHai = { "Budong", "Buxi" };             dic.Add("ZJ", ZheJiang);             dic.Add("SH", ShangHai);             Console.WriteLine("Output :" + dic["ZJ"][0]);         }

  3、用法3: Dictionary的Value為一個類

       //Dictionary的Value為一個類       public static void DicSample3()        {            Dictionary<String, Student> stuList = new Dictionary<String, Student>();            Student stu = null;            for (int i = 0; i < 3; i++ )            {                stu = new Student();                stu.Name = i.ToString();                stu.Name = "StuName" + i.ToString();                stuList.Add(i.ToString(), stu);            }            foreach (var student in stuList)            {                Console.WriteLine("Output : Key {0}, Num : {1}, Name {2}", student.Key, student.Value.Name, student.Value.Name);            }        }

  

Student類:

    public class Student    {        public String Num { get; set; }        public String Name { get; set; }    }

  

 4 備忘:Dictionary的擴充方法使用

 

        /// <summary>        /// Dictionary的擴充方法使用        /// </summary>         public static void DicSample4()         {             //1)普通調用             Dictionary<int, String> dict = new Dictionary<int, String>();             DictionaryExtensionMethodClass.TryAdd(dict, 1, "ZhangSan");             DictionaryExtensionMethodClass.TryAdd(dict, 2, "WangWu");             DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "WangWu");             DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "ZhangWu");             DictionaryExtensionMethodClass.TryAdd(dict, 2, "LiSi");             //2)TryAdd 和 AddOrReplace 這兩個方法具有較強自我描述能力,用起來很省心,而且也簡單:             dict.AddOrPeplace(20, "Orange");             dict.TryAdd(21, "Banana");             dict.TryAdd(22, "apple");             //3)像Linq或jQuery一樣連起來寫                dict.TryAdd(10, "Bob")                 .TryAdd(11, "Tom")                 .AddOrPeplace(12, "Jom");             //4) 擷取值             String F = "Ba";             dict.TryGetValue(31, out F);             Console.WriteLine("F : {0}",F);             foreach (var dic in dict)             {                 Console.WriteLine("Output : Key : {0}, Value : {1}", dic.Key, dic.Value);             }             //5)下面是使用GetValue擷取值             var v1 = dict.GetValue(111,null);             var v2 = dict.GetValue(10,"abc");             //6)大量新增             var dict1 = new Dictionary<int,int>();             dict1.AddOrPeplace(3, 3);             dict1.AddOrPeplace(5, 5);             var dict2 = new Dictionary<int, int>();             dict2.AddOrPeplace(1, 1);             dict2.AddOrPeplace(4, 4);             dict2.AddRange(dict1, false);         }

  擴充方法所在的類

    public static class DictionaryExtensionMethodClass     {        /// <summary>        /// 嘗試將鍵和值添加到字典中:如果不存在,才添加;存在,不添加也不拋導常        /// </summary>        public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)        {            if (dict.ContainsKey(key) == false)                dict.Add(key, value);            return dict;        }        /// <summary>        /// 將鍵和值添加或替換到字典中:如果不存在,則添加;存在,則替換        /// </summary>        public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)        {            dict[key] = value;            return dict;        }        /// <summary>        /// 擷取與指定的鍵相關聯的值,如果沒有則返回輸入的預設值        /// </summary>        public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)        {            return dict.ContainsKey(key)?dict[key] : defaultValue;        }        /// <summary>        /// 向字典中大量新增索引值對        /// </summary>        /// <param name="replaceExisted">如果已存在,是否替換</param>        public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)        {            foreach (var item in values)            {                if (dict.ContainsKey(item.Key) == false || replaceExisted)                    dict[item.Key] = item.Value;            }            return dict;        }    }

參考資料

 

 

  

聯繫我們

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