Yevgeni Grinberg
Yevgeni Grinberg

Reputation: 357

SortedList vs. KeyedCollection

I've been using SortedList(key,value) a lot lately, but I would like to know how it is different than KeyedCollection(key, value), except for the obvious sorting part.

For example, if I'm building a class that requires capabilities of retrieving items by their keys and their sorting is not that important, which one of the following is the better option?:

  1. SortedList as an attribute of the class:

    public class MyClass<TKey,TItem>
    {
        private SortedList<TKey, TItem> myList;
    }
    

    or

  2. Extending KeyedCollection

    public class MyClass<TKey,TItem> : KeyedCollection<TKey,TItem>{}
    

Thank You.

Upvotes: 1

Views: 501

Answers (1)

Prokurors
Prokurors

Reputation: 2548

KeyedCollection is an abstract class - You must create Your type ("MyKeyedDictionary") that derives from KeyedCollection, and You must specify how it will extract TKey from TValue (override TKey GetKeyForItem(TValue) method)

So when You will add values to MyKeyedDictionary, You will have to specify only TValue (and Your class will extract the TKey behind the scenes.

One more difference of KeyedCollection is that it is storing it's data back the scenes in both HashTable and in List, but SortedList is storing data only in List (actually two lists - one storing keys, and other storing values. And it is stored by key ofcourse)

So the SortedList is NOT about sorting values, but about FAST lookups. Main problem is that it is slow on any modifications. But there is a good alternative, that will also have good modification speed - and that alternative is SortedDictionary. It also provides fast lookups, but also has good modification performance.

P.S. SortedDictionary is storing keys in balanced tree, I am not sure how that compares in terms of lookup speed to SortedList's keys, that are stored in sorted list. But from what I have read - both provide fast lookups.

Upvotes: 1

Related Questions