C# 字典 Dictionary


   最近悟出來一個道理,在這兒分享給大家:學歷代表你的過去,能力代表你的現在,學習代表你的將來。我們都知道計算機技術發展日新月異,速度驚人的快,你我稍不留神,就會被慢慢淘汰!因此:每日不間斷的學習是避免被淘汰的不二法寶。

   

Dictionary( TKey , TValue )

表示鍵和值的集合。

Dictionary( TKey, TValue) 泛型類提供了從一組鍵到一組值的映射。字典中的每個添加項都由一個值及其相關聯的鍵組成。通過鍵來檢索值的速度是非常快的,接近於 O(1),這是因為Dictionary( TKey, TValue) 類是作為一個哈希表來實現的。(檢索速度取決於為 TKey 指定的類型的哈希算法的質量。)

只要對象用作 Dictionary( TKey, TValue) 中的鍵,它就不能以任何影響其哈希值的方式更改。使用字典的相等比較器比較時,Dictionary( TKey, TValue) 中的任何鍵都必須是唯一的。鍵不能為 null 。 但是如果值類型 TValue 為引用類型,該值則可以為空。

   老生常談的問題,在此貼上代碼細則如下:

class Program
        {
           static Dictionary<string, int> dic = new Dictionary<string, int>();
            static void Main(string[] args)
            {
                LoadData();
                //推薦用法 取鍵值
                foreach (var item in dic)
                {
                    Console.WriteLine(item.Key);
                }
                //取鍵值
                foreach (KeyValuePair<string, int> kv in dic)
                {

                    Console.WriteLine(kv.Key + kv.Value);

                }
                //取鍵值
                foreach (string key in dic.Keys)
                {

                    Console.WriteLine(key + dic[key]);

                }
                //直接取值
                foreach (int val in dic.Values)
                {

                    Console.WriteLine(val);

                }

                //For循環遍歷
                List<string> test = new List<string>(dic.Keys);
                for (int i = 0; i < dic.Count; i++)
                {

                    Console.WriteLine(test[i] + dic[test[i]]);

                }
                Console.ReadKey();
            }

          
            /// <summary>
            /// 中國大姓氏
            /// </summary>
            private static void LoadData()
            {
                dic.Add("", 1);
                dic.Add("", 2);
                dic.Add("", 3);
                dic.Add("", 4);
                dic.Add("", 5);
                dic.Add("", 6);
                dic.Add("", 7);
                dic.Add("", 8);
                dic.Add("", 9);
                dic.Add("", 10);
                dic.Add("", 11);
                dic.Add("", 12);
            }
        }

   閑着沒事,溫故而知新,隨便寫寫!

   @陳卧龍的博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM