Partager via


Choosing a Collection Class

 

I see quite often customer asking what is the right type of collection for specific purpose and performance overhead versus flexibility. This is again a passionate topic and it’s easy to get into debate with your colleagues especially during the peer code review processes.

Choosing the right Collections class must be done carefully. Using the wrong collection can unnecessarily restrict how you use it.

Consider the following questions:

Do you need temporary storage?

  • If yes, consider Queue or Stack.
  • If no, consider the other collections.

 

Do you need to access the elements in a certain order, such as first-in-first-out, last-in-first-out, or randomly?

  • The Queue offers first-in, first-out access.
  • The Stack offers last-in, first-out access.
  • The rest of the collections offer random access.

 

Do you need to access each element by index?

  • ArrayList and StringCollection offer access to their elements by the zero-based index.
  • Hashtable, SortedList, ListDictionary, and StringDictionary offer access to their elements by the key of the element.
  • NameObjectCollectionBase and NameValueCollection offer access to their elements either by the zero-based index or by the key of the element.

 

Will each element contain just one value or a key-singlevalue pair or a key-multiplevalues combination?

  • One value: Use any of the collections based on IList.
  • Key-singlevalue pair: Use any of the collections based on IDictionary.
  • Key-multiplevalues combination: Consider using or deriving from the NameValueCollection class in the Collections.Specialized namespace.

 

Do you need to sort the elements differently from how they were entered?

  • Hashtable sorts the elements by the hash code of the key.
  • SortedList sorts the elements by the key, based on an IComparer implementation.
  • ArrayList provides a Sort method that takes an IComparer implementation as a parameter.

 

Do you need fast searches and retrieval of information?

  • ListDictionary is faster than Hashtable for small collections of ten items or less.

 

Do you need collections that accept only strings?

  • StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the Collections.Specialized namespace.
  • Generic List<string>

 

Hope this is useful to you when you make the choice about the collections!