要使用Dictionary集合,需要導入C#泛型命名空間
System.Collections.Generic(程序集:mscorlib)
Dictionary的描述
1、從一組鍵(Key)到一組值(Value)的映射,每一個添加項都是由一個值及其相關連的鍵組成
2、任何鍵都必須是唯一的
3、鍵不能為空引用null(VB中的Nothing),若值為引用類型,則可以為空值
4、Key和Value可以是任何類型(string,int,custom class 等)
Dictionary常用用法:以 key 的類型為 int , value的類型為string 為例
1、創建及初始化
代碼如下:
Dictionary<int,string>myDictionary=newDictionary<int,string>();
2、添加元素
代碼如下:
myDictionary.Add(1,"C#");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");
3、通過Key查找元素
代碼如下:
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
4、通過KeyValuePair遍歷元素
代碼如下:
foreach(KeyValuePair<int,string>kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
{
Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}
5、僅遍歷鍵 Keys 屬性
代碼如下:
Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;
foreach(intkeyinkeyCol)
{
Console.WriteLine("Key = {0}", key);
}
foreach(intkeyinkeyCol)
{
Console.WriteLine("Key = {0}", key);
}
6、僅遍歷值 Valus屬性
代碼如下:
Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;
foreach(stringvalueinvalueCol)
{
Console.WriteLine("Value = {0}", value);
}
foreach(stringvalueinvalueCol)
{
Console.WriteLine("Value = {0}", value);
}
7、通過Remove方法移除指定的鍵值
代碼如下:
myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
Console.WriteLine("不存在 Key : 1");
}
if(myDictionary.ContainsKey(1))
{
Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
Console.WriteLine("不存在 Key : 1");
}
其它常見屬性和方法的說明:
Comparer: | 獲取用於確定字典中的鍵是否相等的 IEqualityComparer。 |
Count: | 獲取包含在 Dictionary中的鍵/值對的數目。 |
Item: | 獲取或設置與指定的鍵相關聯的值。 |
Keys: | 獲取包含 Dictionary中的鍵的集合。 |
Values: | 獲取包含 Dictionary中的值的集合。 |
Add: | 將指定的鍵和值添加到字典中。 |
Clear: | 從 Dictionary中移除所有的鍵和值。 |
ContainsKey: | 確定 Dictionary是否包含指定的鍵。 |
ContainsValue: | 確定 Dictionary是否包含特定值。 |
GetEnumerator: | 返回循環訪問 Dictionary的枚舉數。 |
GetType: | 獲取當前實例的 Type。 (從 Object 繼承。) |
Remove: | 從 Dictionary中移除所指定的鍵的值。 |
ToString: | 返回表示當前 Object的 String。 (從 Object 繼承。) |
TryGetValue: | 獲取與指定的鍵相關聯的值。 |