1. 程式人生 > >鍵值對Dictionary、KeyValuePair、Hashtable 簡單使用。

鍵值對Dictionary、KeyValuePair、Hashtable 簡單使用。

KeyValuePair是單個的鍵值對物件。KeyValuePair可用於接收combox選定的值。

例如:KeyValuePair<string, object> par = (KeyValuePair<string, object>)shoplistcomboBox.SelectedItem;

單執行緒程式中推薦使用 Dictionary, 有泛型優勢, 且讀取速度較快, 容量利用更充分。

Hashtable是一個集合。在多執行緒程式中推薦使用 Hashtable, 預設的 Hashtable 允許單執行緒寫入, 多執行緒讀取, 對 Hashtable 進一步呼叫 Synchronized() 方法可以獲得完全執行緒安全的型別. 而 Dictionary 非執行緒安全, 必須人為使用 lock 語句進行保護, 效率大減。

1.鍵值對Dictionary:Dictionary<string,string>鍵值對的使用

複製程式碼

public void CreateDictionary()
{
    Dictionary<string,string> dic=new Dictionary<string,string>();
    //新增
    dic.Add("1","one");
    dic.Add("2","two");
    //取值
    string getone=dic["1"];
}

複製程式碼

2.鍵值對KeyValuePair:KeyValuePair<string,string>

因為KeyValuePair是單個的鍵值對物件,可以用來遍歷Dictionary字典,或儲存combox選擇的值。

複製程式碼

public void usekeyvaluepair()
{
    foreach (KeyValuePair<string, string> item in dic)
    {
        string a = item.Key;
        string b = item.Value;
    }
}

複製程式碼

3.雜湊集合Hashtable

Hashtable是非泛型集合,所以在檢索和儲存值型別時通常會發生裝箱與拆箱的操作。

複製程式碼

public void CreateHashtable()
{
    Hashtable hs = new Hashtable();
    hs.Add(1,"one");
    hs.Add("2","two");
    string a=hs[1].ToString();
    string b = hs["2"].ToString();
}

複製程式碼

 Hashtable集合補充:遍歷集合,可使用DictionaryEntry類(定義可設定或檢索的鍵值對)

複製程式碼

Hashtable hs = new Hashtable();
hs.Add(1, "one");
hs.Add("2", "two");
 foreach (DictionaryEntry item in hs)
{
      string a = item.Key.ToString();
      string b = item.Value.ToString();
}

複製程式碼

使用foreach遍歷是不能修改值的,只能讀取值,迭代變數相當於一個區域性只讀變數。可使用for迴圈修改。

轉自部落格園,博主:小丿悠悠