簡介
在C#中,Dictionary提供快速的基於兼職的元素尋找。當你有很多元素的時候可以使用它。它包含在System.Collections.Generic名空間中。
在使用前,你必須聲明它的鍵類型和實值型別。
詳細說明
必須包含名空間System.Collection.Generic
Dictionary裡面的每一個元素都是一個索引值對(由二個元素組成:鍵和值)
鍵必須是唯一的,而值不需要唯一的
鍵和值都可以是任何類型(比如:string, int, 自訂類型,等等)
通過一個鍵讀取一個值的時間是接近O(1)
索引值對之間的偏序可以不定義
建立和初始化一個Dictionary對象
Dictionary myDictionary = new Dictionary();
添加鍵
static void Main(string[] args)
{
Dictionary d = new Dictionary();
d.Add("C#", 2);
d.Add("C", 0);
d.Add("C++", -1);
}
尋找鍵
static void Main(string[] args)
{
Dictionary d = new Dictionary();
d.Add("C#", 2);
d.Add("VB", 1);
d.Add("C", 0);
d.Add("C++", -1);
if (d.ContainsKey("VB")) // True
{
int p = d["VB"];
Console.WriteLine(p);
}
if (d.ContainsKey("C"))
{
int p1 = d["C"];
Console.WriteLine(p1);
}
}
刪除元素
static void Main(string[] args)
{
Dictionary d = new Dictionary();
d.Add("C#", 2);
d.Add("VB", 1);
d.Add("C", 0);
d.Add("C++", -1);
d.Remove("C");
d.Remove("VB");
}
使用ContainsValue尋找值的存在
static void Main(string[] args)
{
Dictionary d = new Dictionary();
d.Add("C#", 2);
d.Add("VB", 1);
d.Add("C", 0);
d.Add("C++", -1);
if (d.ContainsValue(1))
{
Console.WriteLine("VB");
}
if (d.ContainsValue(2))
{
Console.WriteLine("C#");
}
if (d.ContainsValue(0))
{
Console.WriteLine("C");
}
if (d.ContainsValue(-1))
{
Console.WriteLine("C++");
}
}
KeyNotFoundException
如果你嘗試讀取字典中一個不存在的鍵,那麼你會得到一個KeyNotFoundException。所有在讀取一個鍵之前,你必須先使用ContainKey來核對鍵是否存在字典中。
基於int鍵的Dictionary
static void Main(string[] args)
{
Dictionary d = new Dictionary();
d.Add(1000, "Planet");
d.Add(2000, "Stars");
// lookup the int in the dictionary.
if (d.ContainsKey(1000))
{
Console.WriteLine(true);
}
Console.ReadLine();
}
排序字典SortedDictionary
在排序字典中,當添加元素時字典必須進行排序,所以插入的速度會比較慢點。但是因為元素是有序儲存的,所以元素的尋找可以使用二分搜尋等一些效率更高的搜尋。