Dictionary or KeyedCollection?
I have a class (SomeClass
) which contains a property Name
of string
type. And I need to store an array of that class and find its items by their names. For this purpose there are two types of collections: KeyedCollection
and Dictionary
. My question is: What difference between them and in such case It is better to use KeyedCollection
and Dictionary
? Thanks for any help in explanation.
None of the previous comments address the most important difference between the two: KeyedCollection keeps your items in the order in which they are added (the first item added is at index 0 and the last added is at the last index). Dictionary does not (or at least it is never guaranteed to do so).
This extra benefit of KeyedCollection does have a small performance cost. Under the covers, you pay the cost of maintaining both a Dictionary and a List.
Here is good explanation about differences between Dictionary and KeyedCollection: http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx
Main points are:
- KeyedCollection is abstract, so you can't use it directly.
- KeyedCollection is useful for cases, when key is in entity itself, then you can encapsulate key retrieval within collection implementation.
- There are generic implementations for KeyedCollection (not in the framework though), which allow you to paste key retrieval delegate in collection constructor, so you don't have to repeat it each time you add item.
Update: as long as original link to article was removed, adding link to web archive: https://web.archive.org/web/20200228045828/http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx