键值对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循环修改。

KeyValuePair 和 Dictionary 的关系
1、KeyValuePair 
    a、KeyValuePair 是一个结构体(struct);
    b、KeyValuePair 只包含一个Key、Value的键值对。
2、Dictionary 
    a、Dictionary 可以简单的看作是KeyValuePair 的集合;
    b、Dictionary 可以包含多个Key、Value的键值对。

下面的代码可能会帮助更好的理解它们之间的关系:

Dictionary<int, string> myDic = new Dictionary<int, string>();  
foreach (KeyValuePair<int, string> item in myDic)  
{  
    Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);  


原文地址:https://www.cnblogs.com/wwwbdabc/p/10332820.html