C 中的Dictionary簡介

2021-07-04 20:13:43 字數 3070 閱讀 5549

簡介

在c#中,dictionary提供快速的基於鍵值的元素查詢。當你有很多元素的時候可以使用它。它包含在system.collections.generic名空間中。

在使用前,你必須宣告它的鍵型別和值型別。

詳細說明

必須包含名空間system.collection.generic

dictionary裡面的每乙個元素都是乙個鍵值對(由二個元素組成:鍵和值)

鍵必須是唯一的,而值不需要唯一的

鍵和值都可以是任何型別(比如:string, int, 自定義型別,等等)

通過乙個鍵讀取乙個值的時間是接近o(1)

鍵值對之間的偏序可以不定義

建立和初始化乙個dictionary物件

dictionary mydictionary = new dictionary();

新增鍵static void main(string args)

查詢鍵static void main(string args)

if (d.containskey("c")) }

刪除元素

static void main(string args)

使用containsvalue查詢值的存在

static void main(string args)

if (d.containsvalue(2))

if (d.containsvalue(0))

if (d.containsvalue(-1))

} keynotfoundexception

如果你嘗試讀取字典中乙個不存在的鍵,那麼你會得到乙個keynotfoundexception。所有在讀取乙個鍵之前,你必須先使用containkey來核對鍵是否存在字典中。

基於int鍵的dictionary

static void main(string args)

console.readline();

} 排序字典sorteddictionary

在排序字典中,當新增元素時字典必須進行排序,所以插入的速度會比較慢點。但是因為元素是有序儲存的,所以元素的查詢可以使用二分搜尋等一些效率更高的搜尋。

總結在這篇文章中,簡要地介紹c#中的dictionary的使用。動手寫寫吧~

[csharp]view plain

copy

using system;   

using system.collections.generic;   

class dictionarydemo   

/// 

/// 一般用法 

/// 

static

void dictionarydemo001()   

//遍歷keys 

foreach (var item in dict.keys)   

", item);   

}   

//遍歷values 

foreach (var item in dict.values)   

", item);   

}   

//遍歷整個字典 

foreach (var item in dict)   

value:", item.key, item.value);   

}   

}   

/// 

/// 引數為其它型別 

/// 

static

void dictionarydemo002()   

/// 

/// 呼叫自定義類 

/// 

static

void dictionarydemo003()   

foreach (var item in dict)   

one: username:", item.key, item.value.usercode, item.value.username);   

}   

}   

}   

class yongfa365   

public

string username    

}   

[csharp]view plain

copy

using system;   

using system.collections.generic;   

class dictionarydemo   

/// 

/// 一般用法 

/// 

static

void dictionarydemo001()   

//遍歷keys 

foreach (var item in dict.keys)   

", item);   

}   

//遍歷values 

foreach (var item in dict.values)   

", item);   

}   

//遍歷整個字典 

foreach (var item in dict)   

value:", item.key, item.value);   

}   

}   

/// 

/// 引數為其它型別 

/// 

static

void dictionarydemo002()   

/// 

/// 呼叫自定義類 

/// 

static

void dictionarydemo003()   

foreach (var item in dict)   

one: username:", item.key, item.value.usercode, item.value.username);   

}   

}   

}   

class yongfa365   

public

string username    

}  

C 中的Dictionary簡介

簡介 在c 中,dictionary提供快速的基於鍵值的元素查詢。當你有很多元素的時候可以使用它。它包含在system.collections.generic名空間中。在使用前,你必須宣告它的鍵型別和值型別。詳細說明 必須包含名空間system.collection.generic dictiona...

C 中的Dictionary簡介

簡介 在c 中,dictionary提供快速的基於鍵值的元素查詢。當你有很多元素的時候可以使用它。它包含在system.collections.generic名空間中。在使用前,你必須宣告它的鍵型別和值型別。詳細說明 必須包含名空間system.collection.generic dictiona...

C 中的Dictionary簡介

簡介 在c 中,dictionary提供快速的基於兼職的元素查詢。當你有很多元素的時候可以使用它。它包含在system.collections.generic名空間中。在使用前,你必須宣告它的鍵型別和值型別。詳細說明 必須包含名空間system.collection.generic dictiona...