C#集合類:Dictionary泛型集合

 Dictionary是C#中替代原C++ STL模板庫中map的集合類型,轉載其用法以做備份。

轉自http://whx.tzgt.gov.cn/newOperate/html/1/12/123/9301.html
http://www.cnblogs.com/cnherman/articles/1034861.html

 泛型最常見的用途是泛型集合,命名空間System.Collections.Generic 中包含了一些基於泛型的集合類,使用泛型集合類可以提供更高的類型安全性,還有更高的性能,避免了非泛型集合的重複的裝箱和拆箱。 
    很多非泛型集合類都有對應的泛型集合類,下面是常用的非泛型集合類以及對應的泛型集合類:

非泛型集合類泛型集合類
ArrayListList
HashTableDIctionary
QueueQueue
StackStack
SortedListSortedList

    我們用的比較多的非泛型集合類主要有 ArrayList類 和 HashTable類。我們經常用HashTable 來存儲將要寫入到數據庫或者返回的信息,在這之間要不斷的進行類型的轉化,增加了系統裝箱和拆箱的負擔,如果我們操縱的數據類型相對確定的化  用 Dictionary集合類來存儲數據就方便多了,例如我們需要在電子商務網站中存儲用戶的購物車信息( 商品名,對應的商品個數)時,完全可以用 Dictionary 來存儲購物車信息,而不需要任何的類型轉化。

    下面是簡單的例子,包括聲明,填充鍵值對,移除鍵值對,遍歷鍵值對
    Dictionary<stringstring> myDic = new Dictionary<stringstring>();
    myDic.Add(
"aaa""111");
    myDic.Add(
"bbb""222");
    myDic.Add(
"ccc""333");
    myDic.Add(
"ddd""444");
    
//如果添加已經存在的鍵,add方法會拋出異常
    try
    
{
        myDic.Add(
"ddd","ddd");
    }

    
catch (ArgumentException ex)
    
{
        Console.WriteLine(
"此鍵已經存在:" + ex.Message);
    }

    
//解決add()異常的方法是用ContainsKey()方法來判斷鍵是否存在
    if (!myDic.ContainsKey("ddd"))
    
{
        myDic.Add(
"ddd""ddd");
    }

    
else
    
{
        Console.WriteLine(
"此鍵已經存在:");
    
    }


    // The Add method throws an exception if the new key is 
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = /"txt/" already exists.");
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = /"rtf/", value = {0}.", openWith["rtf"]);

// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console.WriteLine("For key = /"tif/", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key = /"tif/" is not found.");
}
    //而使用索引器來負值時,如果建已經存在,就會修改已有的鍵的鍵值,而不會拋出異常
    myDic ["ddd"]="ddd";
    myDic[
"eee"= "555";
    
    
//使用索引器來取值時,如果鍵不存在就會引發異常
    try
    
{
        Console.WriteLine(
"不存在的鍵/"fff/"的鍵值爲:" + myDic["fff"]);
    }

    
catch (KeyNotFoundException ex)
    
{
        Console.WriteLine(
"沒有找到鍵引發異常:" + ex.Message);
    }

    
//解決上面的異常的方法是使用ContarnsKey() 來判斷時候存在鍵,如果經常要取健值得化最好用 TryGetValue方法來獲取集合中的對應鍵值
    string value = "";
    
if (myDic.TryGetValue("fff"out value))
    
{
        Console.WriteLine(
"不存在的鍵/"fff/"的鍵值爲:" + value );
    }

    
else
    
{     
        Console.WriteLine(
"沒有找到對應鍵的鍵值"); 
    }


    // ContainsKey can be used to test keys before inserting them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = /"ht/": {0}", openWith["ht"]);
}    
    //下面用foreach 來遍歷鍵值對
    
//泛型結構體 用來存儲健值對
    foreach (KeyValuePair<stringstring> kvp in myDic)
    
{
        Console.WriteLine(
"key={0},value={1}", kvp.Key, kvp.Value);
    }

    
//獲取值得集合
    foreach (string s in myDic.Values)
    
{
        Console.WriteLine(
"value={0}", s);
    }

    
//獲取值得另一種方式
    Dictionary<stringstring>.ValueCollection values = myDic.Values;
    
foreach (string s in values)
    
{
        Console.WriteLine(
"value={0}", s);
    }

    // To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl = openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console.WriteLine("/nRemove(/"doc/")");
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key /"doc/" is not found.");
}


常用的屬性和方法如下:

 

 

常用屬性

屬性說明

 

Comparer

獲取用於確定字典中的鍵是否相等的 IEqualityComparer

 

Count

獲取包含在 Dictionary 中的鍵/值對的數目。

 

Item

獲取或設置與指定的鍵相關聯的值。

 

Keys

獲取包含 Dictionary 中的鍵的集合。

 

Values

獲取包含 Dictionary 中的值的集合。

 常用的方法方法說明

 

Add

將指定的鍵和值添加到字典中。

 

Clear

 Dictionary 中移除所有的鍵和值。


ContainsKey

確定 Dictionary 是否包含指定的鍵。

 

ContainsValue

確定 Dictionary 是否包含特定值。

 

Equals 

已重載。 確定兩個 Object 實例是否相等。 (從 Object 繼承。)

 

GetEnumerator

返回循環訪問 Dictionary 的枚舉數。

 

GetHashCode 

用作特定類型的哈希函數。GetHashCode 適合在哈希算法和數據結構(如哈希表)中使用。 (從 Object 繼承。)

 

GetObjectData

實現 System.Runtime.Serialization.ISerializable 接口,並返回序列化 Dictionary 實例所需的數據。

 

GetType 

獲取當前實例的 Type。 (從 Object 繼承。)

 

OnDeserialization

實現 System.Runtime.Serialization.ISerializable 接口,並在完成反序列化之後引發反序列化事件。

 

ReferenceEquals 

確定指定的 Object 實例是否是相同的實例。 (從 Object 繼承。)

 

Remove

 Dictionary 中移除所指定的鍵的值。

 

ToString 

返回表示當前 Object  String。 (從 Object 繼承。)

 

TryGetValue

獲取與指定的鍵相關聯的值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章