Why is there only a SortedList<TKey, TValue>
which looks more like a dictionary, but no SortedList<T>
that is actually just a list that is always sorted?
According to the MSDN documentation on SortedList, it is actually internally implemented as a dynamically-sized array of KeyValuePair<TKey, TValue>
that is always sorted by the key. Wouldn’t the same class be more useful as a list of any type T
? Wouldn’t that fit the name better, too?
Although nobody can really tell you why there is no
SortedList<T>
, it is possible to discuss whySortedList
takes a key and a value. A dictionary maps keys to values. The typical ways to do this are with a binary tree, a hash table, and a list (array), though hash tables are most common because they are O(1) for most operations.The primary operation that it doesn't support in O(1) is getting the next key in order. If you want to be able to do that, you typically use a binary tree, giving you a sorted dictionary.
If you decide to implement the map as a list, you would keep the elements sorted by key so that lookup is O(lg n), giving you another sorted dictionary -- in the form of a sorted list. Of course the name
SortedDictionary
was already taken, butSortedList
wasn't. I might have called itSortedListDictionary
orSortedDictionaryList
, but I didn't get to name it.RPM comments is quite valid. Also, with the Linq extensions, you can do sort by any property of T using the Sort extension method. I think that might be the main reasoning behind it.
There is now :)
I think the way to go with this problem is to implement an extension method that adds to
List<T>
in a sorted manner (just 2 lines of code ;), and thenList<T>
can be used as a sorted list (assuming you avoid usingList.Add(...)
):I think the reason is probably just that
List<T>
already hasBinarySearch
andInsert
, which means implementing your own always-sorted list is trivial.Not that this means a
SortedList<T>
class doesn't belong in the framework -- just that it probably wasn't a very high priority since it could easily be written quickly by any developer who needed it.I think the same was true for
HashSet<T>
, which didn't originally exist because you could easily use aDictionary<T, byte>
(for example) to simulate one before .NET 3.5.I know that's what I did in both cases: I had a
UniqueSet<T>
class and anAlwaysSortedList<T>
class, which just wrapped aDictionary<T, byte>
and aList<T>
(and usedBinarySearch
andInsert
), respectively.It is a list with the sorting being done by the key. I'm just speculating but by providing the ability to specify the key separate from the element, your element doesn't have to be comparable -- only the key need be. I would imagine that in the general case this saves a fair amount of code being developed to implement IComparable since the key is likely a type that is already comparable.