c # Foundations Dictionary

1, to set the Dictionary, C # generics need to import the namespace
the System.Collections.Generic (Assembly: mscorlib)
 

2, Description
1), to a set value (Value) of the mapping from a set of keys (Key), each entry is added by one key value and its associated connected composition
2), any key must be unique
3 ), the key can not be referenced null (Nothing VB in) is empty, if the value is a reference type, it can be empty value
4), key and value can be of any type (string, int, custom class, etc.)

 

    //创建字典
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "1");

            dic.Add(5, "5");

            dic.Add(3, "3");

            dic.Add(2, "2");

            dic.Add(4, "4");
            //给dic进行排序
            var result = from a in dic orderby a.Key select a;

            //遍历元素
            foreach(KeyValuePair<int,string>pair in result)
            {

                Console.WriteLine("key:'{0}',value:'{1}'",pair.Key,pair.Value);
            }

            //只是遍历键
            Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
            foreach (int key in keyCol)
            {
                Console.WriteLine("Key = {0}", key);
            }
            //只遍历值
            Dictionary<int, string>.ValueCollection valueCol = dic.Values;
            foreach (string value in valueCol)
            {
                Console.WriteLine("Value = {0}", value);
            }
         
            Console.Read();

 

Guess you like

Origin www.cnblogs.com/anjingdian/p/10994612.html