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

 

class Program
    {
        static void Main(string[] args)
        {

            Dictionary<int, List<Test>> tesD = new Dictionary<int, List<Test>>();

            List<Test> tList = new List<Test>();

            for (int i = 0; i <= 5; i++)
            {
                Test t1 = new Test();

                t1.Id = i.ToString() + "i";
                t1.Salary = Convert.ToDecimal(i);

                tList.Add(t1);

                for (int y = 0; y <= 5; y++)
                {
                    Test t = new Test();

                    t.Id = y.ToString() + "Y";
                    t.Salary = Convert.ToDecimal(y);

                    tList.Add(t);
                }
                tesD.Add(i, tList);
            }

            if (tesD.ContainsKey(1))
            {

                List<Test> tt = new List<Test>();

                tt.AddRange(tesD[1]);//赋值给tt


            }
             

            Console.Read();
        }
    }

    public class Test
    {
        public string Id { get; set; }

        public Nullable<decimal> Salary { get; set; }

       


    }

 

posted @ 2019-06-09 20:12  安静点--  阅读(440)  评论(0编辑  收藏  举报