c#基础之Dictionary

1、要使用Dictionary集合,需要导入C#泛型命名空间
System.Collections.Generic(程序集:mscorlib)
 

2、描述
1)、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
2)、任何键都必须是唯一的
3)、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
4)、Key和Value可以是任何类型(string,int,custom class 等)

    //创建字典
            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();

猜你喜欢

转载自www.cnblogs.com/anjingdian/p/10994612.html