Jon Skeet
"C# in Depth: What you need to master C# 2 and 3"
3.5.4 SortedList
and SortedDictionary
The naming of SortedList has always bothered me. It feels more like a map or dictionary
than a list. You can access the elements by index as you can for other lists
(although not with an indexer)??”but you can also access the value of each element
(which is a key/value pair) by key. The important part of SortedList is that when you
enumerate it, the entries come out sorted by key. Indeed, a common way of using
SortedList is to access it as a map when writing to it, but then enumerate the entries
in order.
There are two generic classes that map to the same sort of behavior: Sorted-
List and SortedDictionary. (From here on I??™ll just
call them SortedList<,> and SortedDictionary<,> to save space.) They??™re very similar
indeed??”it??™s mostly the performance that differs. SortedList<,> uses less memory,
but SortedDictionary<,> is faster in the general case when it comes to adding entries.
However, if you add them in the sort order of the keys to start with, SortedList<,>
will be faster.
NOTE A difference of limited benefit??”SortedList<,> allows you to find the index of
a particular key or value using IndexOfKey and IndexOfValue, and to
remove an entry by index with RemoveAt. To retrieve an entry by index,
however, you have to use the Keys or Values properties, which implement
IList and IList, respectively.
Pages:
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218