开发手册 欢迎您!
软件开发者资料库

.NET(C#) Dictionary<TKey, TValue>、SortedDictionary<TKey, TValue>和SortedList<TKey,TValue>的使用

1、Dictionary&lt;TKey, TValue&gt;Dictionary&lt;TKey,TValue&gt;泛型类提供一组键到一组值的映射。 每次对字典的添加都包含一个值和与其关联的键。 使用其键检索值的速度非常快,接近 O (1) ,因为 Dictionary&lt;TKey,TVa

1、Dictionary

Dictionary泛型类提供一组键到一组值的映射。 每次对字典的添加都包含一个值和与其关联的键。 使用其键检索值的速度非常快,接近 O (1) ,因为 Dictionary 该类是作为哈希表实现的。检索的速度取决于为指定的类型的哈希算法的质量 TKey

例如,

// 创建一个新的字符串字典,带有字符串键。            //Dictionary openWith =    new Dictionary(); //添加一些元素到字典。没有重复键,但有些值是重复的。openWith.Add("txt", "notepad.exe");openWith.Add("bmp", "paint.exe");openWith.Add("dib", "paint.exe");openWith.Add("rtf", "wordpad.exe"); //如果已经在字典中,则Add方法抛出异常try{    openWith.Add("txt", "winword.exe");}catch (ArgumentException){    Console.WriteLine("一个 Key = \"txt\" 的元素已经存在。");} // Item 属性是索引器的另一个名字,所以访问元素时可以省略其名称。Console.WriteLine("For key = \"rtf\", value = {0}.",    openWith["rtf"]); // 索引器可用于更改值openWith["rtf"] = "winword.exe";Console.WriteLine("For key = \"rtf\", value = {0}.",    openWith["rtf"]); // 如果键不存在,则设置该键的索引器 添加一个新的键/值对。openWith["doc"] = "winword.exe"; // 如果请求的键是索引器,则索引器抛出异常// 不在字典中。try{    Console.WriteLine("For key = \"tif\", value = {0}.",        openWith["tif"]);}catch (KeyNotFoundException){    Console.WriteLine("Key = \"tif\" is not found.");} // 当一个程序经常不得不尝试结果不是的键时// 在字典中,TryGetValue 可以更高效获取值的方法。string value = "";if (openWith.TryGetValue("tif", out value)){    Console.WriteLine("For key = \"tif\", value = {0}.", value);}else{    Console.WriteLine("Key = \"tif\" is not found.");} // ContainsKey 可用于在插入之前判断key是否存在if (!openWith.ContainsKey("ht")){    openWith.Add("ht", "hypertrm.exe");    Console.WriteLine("key = \"ht\": {0}",        openWith["ht"]);} //当使用foreach来枚举字典元素时,元素被检索为KeyValuePair对象。Console.WriteLine();foreach (KeyValuePair kvp in openWith){    Console.WriteLine("Key = {0}, Value = {1}",        kvp.Key, kvp.Value);} // 要单独获取值,请使用values属性。Dictionary.ValueCollection valueColl =    openWith.Values; // ValueCollection的元素是强类型的,具有为字典值指定的类型。Console.WriteLine();foreach (string s in valueColl){    Console.WriteLine("Value = {0}", s);} // 要单独获取键,可使用keys属性。Dictionary.KeyCollection keyColl =    openWith.Keys; // KeyCollection的元素是强类型的,其类型是为字典键指定的。.Console.WriteLine();foreach (string s in keyColl){    Console.WriteLine("Key = {0}", s);} // 使用Remove方法删除键/值对。Console.WriteLine("\nRemove(\"doc\")");openWith.Remove("doc"); if (!openWith.ContainsKey("doc")){    Console.WriteLine("Key \"doc\" is not found.");}

2、SortedDictionary

Dictionary可以使用Linq或者自定义排序,SortDictionary只要插入元素就自动按Key进行了排序。SortedDictionary 需要使用比较器实现来执行键比较。 如果 comparernull ,则此构造函数使用默认的泛型相等比较器Comparer.Default 。 如果类型 TKey 实现 System.IComparable 泛型接口,则默认比较器使用该实现。

例如,

SortedDictionary openWith =                      new SortedDictionary(                      StringComparer.CurrentCultureIgnoreCase); openWith.Add("txt", "notepad.exe");openWith.Add("bmp", "paint.exe");openWith.Add("DIB", "paint.exe");openWith.Add("rtf", "wordpad.exe");try{    openWith.Add("BMP", "paint.exe");}catch (ArgumentException){    Console.WriteLine("\nBMP 已经存在");}// 列出排序字典的内容。Console.WriteLine();foreach (KeyValuePair kvp in openWith){    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,        kvp.Value);}

3、SortedList

SortedDictionarySortedList的功能相同,都用来存储按Key排序的键值对,且无重复。内部实现的差异却很大,SortedDictionary的内部实现是红黑二叉搜索树,而SortedList的内部是两个数组,分别存储KeyValue序列。SortedList的内存占用的少,但是插入的删除的话数组要比树慢。树是O(log2N),数组是O(N)。插入已排序的数据,SortedList比较快。

例如,

// 创建一个新的字符串字典,带有字符串键。            //SortedList openWith =    new SortedList();//添加一些元素到字典。没有重复键,但有些值是重复的。openWith.Add("txt", "notepad.exe");openWith.Add("bmp", "paint.exe");openWith.Add("dib", "paint.exe");openWith.Add("rtf", "wordpad.exe");//如果已经在字典中,则Add方法抛出异常try{    openWith.Add("txt", "winword.exe");}catch (ArgumentException){    Console.WriteLine("一个 Key = \"txt\" 的元素已经存在。");}// Item 属性是索引器的另一个名字,所以访问元素时可以省略其名称。Console.WriteLine("For key = \"rtf\", value = {0}.",    openWith["rtf"]);// 索引器可用于更改值openWith["rtf"] = "winword.exe";Console.WriteLine("For key = \"rtf\", value = {0}.",    openWith["rtf"]);// 如果键不存在,则设置该键的索引器 添加一个新的键/值对。openWith["doc"] = "winword.exe";// 如果请求的键是索引器,则索引器抛出异常// 不在字典中。try{    Console.WriteLine("For key = \"tif\", value = {0}.",        openWith["tif"]);}catch (KeyNotFoundException){    Console.WriteLine("Key = \"tif\" is not found.");}// 当一个程序经常不得不尝试结果不是的键时// 在字典中,TryGetValue 可以更高效获取值的方法。string value = "";if (openWith.TryGetValue("tif", out value)){    Console.WriteLine("For key = \"tif\", value = {0}.", value);}else{    Console.WriteLine("Key = \"tif\" is not found.");}// ContainsKey 可用于在插入之前判断key是否存在if (!openWith.ContainsKey("ht")){    openWith.Add("ht", "hypertrm.exe");    Console.WriteLine("key = \"ht\": {0}",        openWith["ht"]);}//当使用foreach来枚举字典元素时,元素被检索为KeyValuePair对象。Console.WriteLine();foreach (KeyValuePair kvp in openWith){    Console.WriteLine("Key = {0}, Value = {1}",        kvp.Key, kvp.Value);}// 要单独获取值,请使用values属性。IList ilistValues =    openWith.Values;// ValueCollection的元素是强类型的,具有为字典值指定的类型。Console.WriteLine();foreach (string s in ilistValues){    Console.WriteLine("Value = {0}", s);}// 要单独获取键,可使用keys属性。IList ilistKeys =    openWith.Keys;// KeyCollection的元素是强类型的,其类型是为字典键指定的。.Console.WriteLine();foreach (string s in ilistKeys){    Console.WriteLine("Key = {0}", s);}// 使用Remove方法删除键/值对。Console.WriteLine("\nRemove(\"doc\")");openWith.Remove("doc");if (!openWith.ContainsKey("doc")){    Console.WriteLine("Key \"doc\" is not found.");}