Dictionary的基本用法

1.Dictionary<T,T>增加鍵值對之前需要判斷是否存在該鍵,如果已經存在該鍵而且不判斷,拋出異常

2.Dictionary的Value爲一個數組
3.Dicyionary的Value爲一個類

 

                    #region Dictionary 用法總結
			Dictionary<string, string> pList = new Dictionary<string, string>();
			//1.增加鍵值對之前需要判斷是否存在該鍵,如果已經存在該鍵而且不判斷,拋出異常
			try
			{
				if (pList.ContainsKey("Item1Key") == false)
				{
					pList.Add("ItemsKey", "One");
				}
			}
			catch (System.Exception e)
			{
				Console.WriteLine("Eeero:{0}", e.Message);
			}
			//判斷是否存在相應的Key並顯示
			if (pList.ContainsKey("Item1Key"))
			{
				Console.WriteLine("Output:{0}", pList["Item1Key"]);
			}
			//便利遍歷Key
			foreach (var key in pList.Keys)
			{
				Console.WriteLine("Output key:{0}", key);
			}
			//遍歷Value
			foreach (string value in pList.Values)
			{
				Console.WriteLine("Output :value{0}", value);
			}
			//遍歷key和value
			foreach (var dic in pList)
			{
				Console.WriteLine("Output key:{0},value:{1}", dic.Key,dic.Value);
			}
			//2.Dictionary的Value爲一個數組
			Dictionary<string, string[]> AList = new Dictionary<string, string[]>();
			string[] Nums = { "One","Two","Three","Four","Five"};
			string[] Weeks = { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
			AList.Add("Nums", Nums);
			AList.Add("Weeks", Weeks);
			foreach (var dic in AList)
			{
				Console.WriteLine("Output key:{0}", dic.Key);
				foreach (string value in dic.Value)
				{
					Console.WriteLine("Output value:{0}", value);
				}
			}
			//3.Dicyionary的Value爲一個類
			Dictionary<string, Student> sList = new Dictionary<string, Student>();
			Student std = new Student();
			for (int i = 0; i < 5; i++)
			{
				std.c_id = i;
				std.c_name = Nums[i];
				std.c_code = "21012241" + i.ToString();
				std.c_remark = "電子信息科學與技術";
				std.c_db_status = 0;
				sList.Add(i.ToString(), std);
			}
			foreach (var s in sList)
			{
				Console.WriteLine("Output key:{0},c_id:{1},c_code:{2},c_db_status:{3},", s.Value.c_id, s.Value.c_code, s.Value.c_db_status);
			}
                    #endregion

 

Student類:

 

                public Student()
		{ }
		private int _c_id;
		private string _c_code;
		private string _c_name;
		private string _c_remark;
		private int _c_db_status = 0;
		/// <summary>
		/// 
		/// </summary>
		public int c_id
		{
			set { _c_id = value; }
			get { return _c_id; }
		}
		/// <summary>
		/// 
		/// </summary>
		public string c_code
		{
			set { _c_code = value; }
			get { return _c_code; }
		}
		/// <summary>
		/// 
		/// </summary>
		public string c_name
		{
			set { _c_name = value; }
			get { return _c_name; }
		}
		/// <summary>
		/// 
		/// </summary>
		public string c_remark
		{
			set { _c_remark = value; }
			get { return _c_remark; }
		}
		public int c_db_status
		{
			set { _c_db_status = value; }
			get { return _c_db_status; }
		}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章