1.Dictionary:集合中每個元素都包含一組成對的key and Value,可以透過key來查詢到對應的value。
下圖為其實做之介面:
2.IDictionary<TKey,TValue> 介面
IDictionary<TKey,TVaalue> 繼承 ICollection<T>,並使用KeyValuePair<TKey,TValue>來做為集合中元素之類型,
下圖為該介面之定義:
public interface IDictionary<TKey,TValue> : ICollection<KeyValuePair<TKey,TValue>> , IEnumerable
{
bool ContainsKey(TKey key); //檢查某key是否在字典集合中
bool TryGetValue(TKey key , out TValue value); //嘗試取植(取不到不拋出異常)
void Add(TKey key , TValue value); // 加入元素
bool Remove(TKey key); //刪除元素
TValue this [TKey key] { get; set; } // 索引子
ICollection <TKey> keys { get; } // 只傳回TKey集合
ICollection <TValue> Values { get; } //只傳回TValue集合
}
3.加入新元素至Dicitionary集合(兩種做法)
法1: 呼叫Add。
若呼叫Add方法加入新元素,若要加入之key已經存在於Dicitionary中,會拋出異常。
ex.
var dict = new Dictionary<string,int>();
dict.Add("Melo",26);
dict.Add("Melo",27); //這行會發生異常,因為"Melo"已經存在Dictionary中。
法2: 使用索引子的setter。
當使用setter(索引子)來設定某個key所對應之value時,若指定之key已經存在Dicitionary中則會去改變既有元素之value。
反之若key未存在Dicitionary集合中,則會將kye與value加入至Dicitionary中
dict["Melo"] = 27; //不會拋出異常,會去將Melo對應之value修改成27。
Note: 注意法1與法2之不同,法1加入存在之key時會拋出異常,法2則是替代掉對應value。
4.取得DIcitionary集合之元素(兩種做法)
法1:呼叫getter(索引子)
當你使用getter取得某個key索對應之value時,若key不存在,則會拋出異常。
int num1 = dict["abc"]; //這行將拋出異常,因為abc不存在於Dicitonary中。
法2:使用TryGetValue方法
使用此方法將不會拋出異常,只是傳回false 表示取不到key對應之value。
if(dict.TryGetValue("abc",out num2))
{
response.write(num2);
}
使用TryGetValue即使key:"abc"不存在Dicitonary中,也不會拋出異常,只會跳開if往下執行。
若把"abc"改成"Melo"則會將"Melo"對應之值設定給out參數num2,再印出num2
Example:
5.Dicitionary<TKey,TValue>
Dicitionary<TKey,TValue> 實做 IDictionary<TKey,TValue> 且 IDictionary<TKey,TValue>繼承了IEnumerable,
所以也支援元素之尋訪(froeach)。
每一次尋訪取得元素之型別為KeyValuePair<TKey,TValue>結構(可以看到foreach的item型別為KeyValuePair<TKey,TValue>)。
Example: