Specialized Collections

The System.Collections.Specialized namespace contains a series of collections that either are strongly typed or offer functionality that is not widely required.

Strongly Typed Collections

The strongly typed collections all deal exclusively with strings.

NameObjectCollectionBase and NameValueCollection

The NameObjectCollectionBase class is an abstract class that is based on a Hashtable but that accepts only strings as key types. The only concrete implementation of this class in the collections namespace is NameValueCollection. The NameValueCollection class is derived from NameObjectCollectionBase but can be used to store multiple values for each key. However, both the key and the values must be strings. The most obvious use of this class is processing HTTP headers. Here’s an example:

NameValueCollection x_collection = new NameValueCollection();

x_collection.Add("key", "value1");
x_collection.Add("key", "value2");

string[] x_arr = x_collection.GetValues("key");
foreach (string x_str in x_arr) {
    Console.WriteLine("VALUE: " + x_str);
}

The result of this fragment follows:

VALUE: value1
VALUE: value2

StringCollection

The StringCollection class represents an implementation of the IList interface such that the interface handles only strings.

StringDictionary

The StringDictionary class is the dictionary equivalent of the StringCollection class. In essence, it’s an implementation of a Hashtable that accepts only strings as keys.

Unusual Collections

The following two collections have characteristics that make them useful in specific circumstances but not as everyday collections.

ListDictionary

The ListDictionary class implements the IDictionary interface using a single-linked array. It behaves like a Hashtable, which implements the same interface, but is faster when dealing with up to ten items. This is based on the premise that iterating over a small array is faster than computing hash codes. For more than ten items, the iteration takes longer than hashing and the benefits of this class are negated; a Hashtable will offer better performance

HybridDictionary

The HybridDictionary class provides the best of both a ListDictionary and a Hashtable. If the number of elements in the collection is small, they are maintained in a ListDictionary. Once the number goes above what’s optimal for a ListDictionary, they are automatically transferred to a Hashtable for better performance. This results in a one-off performance hit. If the number of elements falls below the ListDictionary threshold, they remain in the Hashtable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset