Dictionary集合
Dictionary<string, string>是一個泛型集合,他本身有集合的功能有時候可以把它看成數組,
他的結構是這樣的:Dictionary<[key], [value]>
他的特點是存入對象是需要與[key]值一一對應的存入該泛型,通過某一個一定的[key]去找到對應的值。
直接看代碼:
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace DictionarySorting { class Program { static void Main(string[] args) { Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(1, "HaHa"); dic.Add(5, "HoHo"); dic.Add(3, "HeHe"); dic.Add(2, "HiHi"); dic.Add(4, "HuHu"); var result = from pair in dic orderby pair.Key select pair; foreach (KeyValuePair<int, string> pair in result) { Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value); } Console.ReadKey(); } } }
Dictionary的基本用法:
假如需求:現在要導入一批數據,這些數據中有一個稱為公司的字段是我們數據庫裏已經存在了的,目前我們需要把每個公司名字轉為ID後才存入數據庫。
分析:每導一筆記錄的時候,就把要把公司的名字轉為公司的ID,這個不應該每次都查詢一下數據庫的,因為這太耗數據庫的性能了。
解決方案:在業務層裏先把所有的公司名稱及相應的公司ID一次性讀取出來,然後存放到一個Key和Value的鍵值對裏,然後實現隻要把一個公司的名字傳進去,就可以得到此公司相應的公司ID,就像查字典一樣。對,我們可以使用字典Dictionary操作這些數據。
示例:SetKeyValue()方法相應於從數據庫裏讀取到了公司信息。
/// <summary> /// 定義Key為string類型,Value為int類型的一個Dictionary /// </summary> /// <returns></returns> protected Dictionary<string, int> SetKeyValue() { Dictionary<string, int> dic = new Dictionary<string, int>(); dic.Add("公司1", 1); dic.Add("公司2", 2); dic.Add("公司3", 3); dic.Add("公司4", 4); return dic; } /// <summary> /// 得到根據指定的Key行到Value /// </summary> protected void GetKeyValue() { Dictionary<string, int> myDictionary = SetKeyValue(); //測試得到公司2的值 int directorValue = myDictionary["公司2"]; Response.Write("公司2的value是:" + directorValue.ToString()); }
最後更新:2017-04-02 06:51:20