欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中Dictionary泛型集合7種常見的用法

 更新時(shí)間:2016年03月28日 11:13:57   作者:jae  
本文主要介紹了Dictionary集合的7種最基礎(chǔ)的用法,包括創(chuàng)建、添加、查找、遍歷、刪除等方法,程序都是由簡入繁,希望能通過閱讀簡單的示例,給大家一些啟發(fā)。

要使用Dictionary集合,需要導(dǎo)入C#泛型命名空間

 System.Collections.Generic(程序集:mscorlib)

 Dictionary的描述
1、從一組鍵(Key)到一組值(Value)的映射,每一個添加項(xiàng)都是由一個值及其相關(guān)連的鍵組成

2、任何鍵都必須是唯一的

3、鍵不能為空引用null(VB中的Nothing),若值為引用類型,則可以為空值

4、Key和Value可以是任何類型(string,int,custom class 等)

 Dictionary常用用法:以 key 的類型為 int , value的類型為string 為例

  1、創(chuàng)建及初始化

 

復(fù)制代碼 代碼如下:
Dictionary<int,string>myDictionary=newDictionary<int,string>();

  2、添加元素

復(fù)制代碼 代碼如下:
myDictionary.Add(1,"C#");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");

  3、通過Key查找元素

復(fù)制代碼 代碼如下:
if(myDictionary.ContainsKey(1))
{
  Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}

  4、通過KeyValuePair遍歷元素

復(fù)制代碼 代碼如下:
foreach(KeyValuePair<int,string>kvp in myDictionary)
{
  Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}

 5、僅遍歷鍵 Keys 屬性

復(fù)制代碼 代碼如下:
Dictionary<int,string>.KeyCollection keyCol=myDictionary.Keys;
foreach(intkeyinkeyCol)
{
  Console.WriteLine("Key = {0}", key);
}

 6、僅遍歷值 Valus屬性

復(fù)制代碼 代碼如下:
Dictionary<int,string>.ValueCollection valueCol=myDictionary.Values;
foreach(stringvalueinvalueCol)
{
  Console.WriteLine("Value = {0}", value);
}

 7、通過Remove方法移除指定的鍵值

復(fù)制代碼 代碼如下:
myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
{
  Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else
{
  Console.WriteLine("不存在 Key : 1");
}

其它常見屬性和方法的說明:

Comparer: 獲取用于確定字典中的鍵是否相等的 IEqualityComparer。
Count: 獲取包含在 Dictionary中的鍵/值對的數(shù)目。
Item: 獲取或設(shè)置與指定的鍵相關(guān)聯(lián)的值。
Keys: 獲取包含 Dictionary中的鍵的集合。
Values: 獲取包含 Dictionary中的值的集合。
Add: 將指定的鍵和值添加到字典中。
Clear: 從 Dictionary中移除所有的鍵和值。
ContainsKey: 確定 Dictionary是否包含指定的鍵。
ContainsValue: 確定 Dictionary是否包含特定值。
GetEnumerator: 返回循環(huán)訪問 Dictionary的枚舉數(shù)。
GetType: 獲取當(dāng)前實(shí)例的 Type。 (從 Object 繼承。)
Remove: 從 Dictionary中移除所指定的鍵的值。
ToString: 返回表示當(dāng)前 Object的 String。 (從 Object 繼承。)
TryGetValue: 獲取與指定的鍵相關(guān)聯(lián)的值。

相關(guān)文章

最新評論