19.2.4 SortedList

SortedList类实现了IDictionary、ICollection以及IEnumerable接口,如图19-12所示。

19.2.4 SortedList - 图1

图 19-12 SortedList类图

和Hashtable类似,SortedList类也表示一个键/值对的集合,可以通过键或索引对元素进行访问,但不同的是,SortedList类支持基于键的排序。在SortedList中,键和值分别保存于一个数组中,当向SortedList类添加一个元素时,SortedList首先会对key进行排序,然后根据排序结果计算出要插入到集合中的位置索引,再分别将key和value插入到各自数组的指定索引位置;当使用foreach循环集合中的元素时,SortedList会将相同索引位置的key和value放进一个DictionaryEntry类型的对象,然后返回,如图19-13所示。

19.2.4 SortedList - 图2

图 19-13 SortedList示意图

将代码清单19-2稍微进行改造,取其部分代码,将openWith的类型从Hashtable改为SortedList,同样还是插入4个元素,如代码清单19-4所示。

代码清单19-4 SortedList示例代码


using System;

using System.Collections;

namespace ProgrammingCSharp4

{

class CollectionSample

{

public static void Main()

{

SortedList openWith=new SortedList();

openWith.Add("txt","notepad.exe");

openWith.Add("bmp","paint.exe");

openWith.Add("dib","paint.exe");

openWith.Add("rtf","wordpad.exe");

foreach(DictionaryEntry de in openWith)

{

Console.WriteLine("Key={0},Value={1}",de.Key,de.Value);

}

}

}

}


注意观察运行结果是否按照key的值进行了排序,上述代码的运行结果如下:


Key=bmp,Value=paint.exe

Key=dib,Value=paint.exe

Key=rtf,Value=wordpad.exe

Key=txt,Value=notepad.exe

请按任意键继续……