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);
            }
        }

   闲着没事,温故而知新,随便写写!

   @陈卧龙的博客