Share via


Selecting a Collection Class 

Be sure to choose your System.Collections class carefully. Using the wrong type can restrict your use of the collection.

Consider the following questions:

  • Do you need a sequential list where the element is typically discarded after its value is retrieved?

    • If yes, consider using the Queue class or the Queue generic class if you need first-in-first-out (FIFO) behavior. Consider using the Stack class or the Stack generic class if you need last-in-first-out (LIFO) behavior.

    • If not, consider using the other collections.

  • Do you need to access the elements in a certain order, such as FIFO, LIFO, or random?

    • The Queue class and the Queue generic class offer FIFO access.

    • The Stack class and the Stack generic class offer LIFO access.

    • The LinkedList generic class allows sequential access either from the head to the tail or from the tail to the head.

    • The rest of the collections offer random access.

  • Do you need to access each element by index?

  • Will each element contain one value, a combination of one key and one value, or a combination of one key and multiple values?

    • One value: Use any of the collections based on the IList interface or the IList generic interface.

    • One key and one value: Use any of the collections based on the IDictionary interface or the IDictionary generic interface.

    • One value with embedded key: Use the KeyedCollection generic class.

    • One key and multiple values: Use the NameValueCollection class.

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

    • The Hashtable class sorts its elements by their hash codes.

    • The SortedList class and the SortedDictionary and SortedList generic classes sort their elements by the key, based on implementations of the IComparer interface and the IComparer generic interface.

    • ArrayList provides a Sort method that takes an IComparer implementation as a parameter. Its generic counterpart, the List generic class, provides a Sort method that takes an implementation of the IComparer generic interface as a parameter.

  • Do you need fast searches and retrieval of information?

    • ListDictionary is faster than Hashtable for small collections (10 items or fewer). The SortedDictionary generic class provides faster lookup than the Dictionary generic class.
  • Do you need collections that accept only strings?

    • StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the System.Collections.Specialized namespace.

    • In addition, you can use any of the generic collection classes in the System.Collections.Generic namespace as strongly typed string collections by specifying the String class for their generic type arguments.

See Also

Reference

System.Collections
System.Collections.Specialized
System.Collections.Generic

Other Resources

Creating and Manipulating Collections