We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
The other day I wan in the need of a sorted collection. I found that there are 2 sorted collections available. SortedDictionary and SortedList. Now let me ask you, what do you think is the difference? Well, my first though was that they are the same except for the keys, which in SortedDictionary have to be unique.
Check out this code:
What do you think will be the output?
I thought that It will be:
I also thought that because the keys are the same you might also get the reversed order:
It seems I was wrong on both my guesses…
The answer is that you will get an ArgumentException exception on line 5 that says : An entry with the same key already exists. WTF!!!!!
Then what is the difference between SortedList and SortedDictionary, a quick search got me to this page: http://msdn.microsoft.com/en-us/library/f7fta44c.aspx and I quote:
The SortedDictionary<(Of <(TKey, TValue>)>) generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this respect, it is similar to the SortedList<(Of <(TKey, TValue>)>) generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:
- SortedList<(Of <(TKey, TValue>)>) uses less memory than SortedDictionary<(Of <(TKey, TValue>)>).
- SortedDictionary<(Of <(TKey, TValue>)>) has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for SortedList<(Of <(TKey, TValue>)>).
- If the list is populated all at once from sorted data, SortedList<(Of <(TKey, TValue>)>) is faster than SortedDictionary<(Of <(TKey, TValue>)>).
Basically what it says is that they are the same. So what is a SortedList good for? beats me. I deem it Useless. After messing around with it some more I found that you cannot access the values by index, meaning: SortedList[i] will not work. What is it good for then?
What should you do instead? you have 2 other options which I will discuss in my next post
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd