Primary Collection Classes

There are six key sets of collection classes, and they differ from each other in terms of how data is inserted, stored, and retrieved. Each generic class is located in the System.Collections.Generic namespace, and their nongeneric equivalents are in the System.Collections namespace.

List Collections: List<T> and ArrayList

The List<T> class, and its nongeneric equivalent, ArrayList, have properties similar to an array. The key difference is that these classes automatically expand as the number of elements increases. (In contrast, an array size is constant.) Furthermore, lists can shrink via explicit calls to TRimToSize() or Capacity (see Figure 12.1 on page 422).

These classes are categorized as list collections whose distinguishing functionality is that each element can be individually accessed by index, just like an array. Therefore, you can set and access elements in the list collection classes using the index operator, where the index parameter value corresponds to the position of an element in the collection. Listing 12.1 shows an example, and Output 12.1 shows the results.

Listing 12.1. Using List<T>

[View full width]

   using System;     using System.Collections.Generic;     class Program     {       static void Main()       {           List<string> list = new List<string>();           // Lists automatically expand as elements           // are added.               list.Add("Sneezy");               list.Add("Happy");               list.Add("Dopey");               list.Add("Doc");               list.Add("Sleepy");               list.Add("Bashful");               list.Add("Grumpy");               list.Sort();               Console.WriteLine("In alphabetical order {0} is the " + "first dwarf while {1 } is the last.", list[0], list[6]);               list.Remove("Grumpy");           }     }  

Output 12.1.

 In alphabetical order Bashful is the first dwarf while Sneezy is the last.  

C# is zero-index based; therefore, index zero in Listing 12.1 corresponds to the first element and index 6 indicates the seventh element. Retrieving elements by index does not involve a search. It involves a quick and simple "jump" operation to a location in memory.

Figure 12.1. List<> and ArrayList Class Diagrams

When you use the Add() method, elements maintain the order in which you added them. Therefore, prior to the call to Sort() in Listing 12.1, "Sneezy" is first and "Grumpy" is last. Although List<T> and ArrayList support a Sort() method, nothing states that all list collections require such a method.

There is no support for automatic sorting of elements as they are added. In other words, an explicit call to Sort() is required for the elements to be sorted (items must implement IComparable). To remove an element, you use the Remove() method.

To search either List<T> or ArrayList for a particular element, you use the Contains(), IndexOf(), LastIndexOf(), and BinarySearch() methods. The first three methods search through the array, starting at the first element (the last element for LastIndexOf()), and examine each element until the equivalent one is found. The execution time for these algorithms is proportional to the number of elements searched before a hit occurs. Be aware that the collection classes do not require that all the elements within the collection are unique. If two or more elements in the collection are the same, then IndexOf() returns the first index and LastIndexOf() returns the last index.

BinarySearch() uses a binary search algorithm and requires that the elements be sorted. A useful feature of the BinarySearch() method is that if the element is not found, a negative integer is returned. The bitwise complement (~) of this value is the index of the next element larger than the element being sought, or the total element count if there is no greater value. This provides a convenient means to insert new values into the list at the specific location so as to maintain sorting (see Listing 12.2).

Listing 12.2. Using the Bit Complement of the BinarySearch() Result

    using System;     using System.Collections.Generic;     class Program     {        static void Main()        {            List<string> list = new List<string>();            int search;            list.Add("public");            list.Add("protected");            list.Add("private");            list.Sort();            search = list.BinarySearch("protected internal");            if (search < 0)            {              list.Insert(~search, "protected internal");            }            foreach (string accessModifier in list)            {                Console.WriteLine(accessModifier);            }        }     }  

Beware that if the list is not first sorted, an element will not necessarily be found, even if it is in the list. The results of Listing 12.2 appear in Output 12.2.

Output 12.2.

 private  protected  protected internal  public  

Advanced Topic: Finding Multiple Items with FindAll()

Sometimes you must find multiple items within a list and your search criteria are more complex than looking for specific values. To support this, System.Collections.Generic.List<T> includes a FindAll() method. FindAll() takes a parameter of type Predicate<T>, which is a reference to a method called a delegate. Listing 12.3 demonstrates how to use the FindAll() method.

Listing 12.3. Demonstrating FindAll() and Its Predicate Parameter

    using System;     using System.Collections.Generic;     class Program     {       static void Main()       {           List<int> list = new List<int>();           list.Add(1);           list.Add(2);           list.Add(3);           list.Add(2);         List<int> results = list.FindAll(Even);                              Assert.AreEqual(2, results.Count);         Assert.IsTrue(results.Contains(2));         Assert.IsFalse(results.Contains(3));       }       public static bool Even(int value)       {           if ((value % 2) == 0)           {               return true;           }           else           {               return false;           }        }     }  

In Listing 12.3's call to FindAll(), you pass a delegate instance, Even(). This method returns true when the integer argument value is even. FindAll() takes the delegate instance and calls into Even() for each item within the list (this listing uses C# 2.0's delegate type inferencing). Each time the return is true, it adds it to a new List<T> instance and then returns this instance once it has checked each item within list. A complete discussion of delegates occurs in Chapter 13.

Dictionary Collections: Dictionary<TKey, TValue> and Hashtable

Another category of collection classes is the dictionary classesspecifically, Dictionary<Tkey, Tvalue> and Hashtable (see Figure 12.2). Unlike the list collections, dictionary classes store name/value pairs. The name functions as a unique key that can be used to look up the corresponding element in a manner similar to that of using a primary key to access a record in a database. This adds some complexity to the access of dictionary elements, but because lookups by key are efficient operations, this is a useful collection. Note that the key may be any data type, not just a string or a numeric value.

Figure 12.2. Dictionary and Hashtable Class Diagrams

One option for inserting elements into a dictionary is to use the Add() method, passing both the key and the value, as shown in Listing 12.4.

Listing 12.4. Adding Items to a Dictionary<TKey, TValue>

    using System;     using System.Collections.Generic;     class Program     {       static void Main()       {           Dictionary<Guid,string> dictionary =                newDictionary<Guid, string>();           Guid key = Guid.NewGuid();           dictionary.Add(key, "object");       }     }  

Listing 12.4 inserts the string "object" using a Guid as its key. If an element with the same key has already been added, an exception is thrown.

An alternative is to use the indexer, as shown in Listing 12.5.

Listing 12.5. Inserting Items in a Dictionary<TKey, TValue> Using the Index Operator

    using System;     using System.Collections.Generic;     class Program     {       static void Main()       {           Dictionary<Guid, string> dictionary = newDictionary<Guid, string>();           Guid key = Guid.NewGuid();           dictionary[key] = "object";           dictionary[key] = "byte";       }     }  

The first thing to observe in Listing 12.5 is that the index operator does not require an integer. Instead, the index data type is specified by the first type parameter, TKey, when declaring a Dictionary<TKey, TValue> variable (in the case of Hashtable, the data type is object). In this example, the key data type used is Guid, and the value data type is string.

The second thing to notice in Listing 12.5 is the reuse of the same index. In the first assignment, no dictionary element corresponds to key. Instead of throwing an out-of-bounds exception, as an array would, dictionary collection classes insert a new object. During the second assignment, an element with the specified key already exists, so instead of inserting an additional element, the existing element corresponding to key is updated from "object" to "byte".

Accessing a value from a dictionary using the index operator ([]) with a nonexistent key throws an exception of type System.Collections.Generic.KeyNotFoundException. The ContainsKey() method, however, allows you to check whether a particular key is used before accessing its value, thereby avoiding the exception. Also, since the keys are stored in a hash algorithm type structure, the search is relatively efficient.

By contrast, checking whether there is a particular value in the dictionary collections is a time-consuming operation with linear performance characteristics. To do this you use the ContainsValue() method, which searches sequentially through each element in the collection.

You remove a dictionary element using the Remove() method, passing the key, not the element value.

There is no particular order for the dictionary classes. Elements are arranged into a hashtable type data structure using hashcodes for rapid retrieval (acquired by calling GetHashCode() on the key). Iterating through a dictionary class using the foreach loop, therefore, accesses values in no particular order. Because both the key and the element value are required to add an element to the dictionary, the data type returned from the foreach loop is KeyValuePair<TKey, TValue> for Dictionary<TKey, TValue>, and DictionaryEntry for Hashtable. Listing 12.6 shows a snippet of code demonstrating the foreach loop with the Dictionary<TKey, TValue> collection class. The output appears in Output 12.3

Listing 12.6. Iterating over Dictionary<TKey, TValue> with foreach

    using System;     using System.Collections.Generic;     class Program     {       static void Main()       {            Dictionary<string,string> dictionary = new                 Dictionary<string,string>();            int index =0;            dictionary.Add(index++.ToString(), "object");            dictionary.Add(index++.ToString(), "byte");            dictionary.Add(index++.ToString(), "uint");            dictionary.Add(index++.ToString(), "ulong");            dictionary.Add(index++.ToString(), "float");            dictionary.Add(index++.ToString(), "char");            dictionary.Add(index++.ToString(), "bool");            dictionary.Add(index++.ToString(), "ushort");            dictionary.Add(index++.ToString(), "decimal");            dictionary.Add(index++.ToString(), "int");            dictionary.Add(index++.ToString(), "sbyte");            dictionary.Add(index++.ToString(), "short");            dictionary.Add(index++.ToString(), "long");            dictionary.Add(index++.ToString(), "void");            dictionary.Add(index++.ToString(), "double");            dictionary.Add(index++.ToString(), "string");            Console.WriteLine("Key  Value   Hashcode");            Console.WriteLine("---  ------  --------");            foreach (KeyValuePair<string, string> i in dictionary)            {                 Console.WriteLine("{0,-5}{1,-9}{2}",                     i.Key, i.Value, i.Key.GetHashCode());            }       }     } 

Output 12.3.

 Key  Value   Hashcode  --- -----------------  0   object   -842352752  1   byte     -842352753  2   uint     -842352754  3   ulong    -842352755  4   float    -842352756  5   char     -842352757  6   bool     -842352758  7   ushort   -842352759  8   decimal  -842352744  9   int      -842352745  10  sbyte    -843401329  11  short    -843466865  12  long     -843532401  13  void     -843597937  14  double   -843663473  15  string   -843729009  

If you want to deal only with keys or only with elements within a dictionary class, they are available via the Keys and Values properties. The data type returned from these properties is of type ICollection, and it is typed in generic or nongeneric form depending on whether a Dictionary<TKey, TValue> or Hashtable collection is used. The data returned by these properties is a reference to the data within the original dictionary collection, so changes within the dictionary are automatically reflected in the ICollection type returned by the Keys and Values properties.

Sorted Collections: SortedDictionary<TKey, TValue> and SortedList<T>

The sorted collection classes (see Figure 12.3 on page 431) differ from unsorted implementation collections in that the elements are sorted by key for SortedDictionary<TKey, TValue> and by value for SortedList<T>. (There is also a nongeneric SortedList implementation.) A foreach iteration of sorted collections returns the elements sorted in key order (see Listing 12.7).

Listing 12.7. Using SortedDictionary<TKey, TValue>

[View full width]

    using System;     using System.Collections.Generic;         class Program     {       static void Main()       {           SortedDictionary<string,string> sortedDictionary = new SortedDictionary<string, string>();           int index =0;           sortedDictionary.Add(index++.ToString(), "object");           // ...          sortedDictionary.Add(index++.ToString(), "string");           Console.WriteLine("Key ValueHashcode");           Console.WriteLine--- -----------------");           foreach (KeyValuePair<string, string> i in sortedDictionary)           {               Console.WriteLine("{0,-5}{1,-9}{2}",                   i.Key, i.Value, i.Key.GetHashCode());           }       }     }  

The results of Listing 12.7 appear in Output 12.4.

Output 12.4.

 Key   Value    Hashcode  --- -----------------  0   object   -842352752  1   byte     -842352753  10  sbyte    -843401329  11  short    -843466865  12  long     -843532401  13  void     -843597937  14  double   -843663473  15  string   -843729009  2   uint     -842352754  3   ulong    -842352755  4   float    -842352756  5   char     -842352757  6   bool     -842352758  7   ushort   -842352759  8   decimal  -842352744  9   int      -842352745  

Note that the elements in the key are in alphabetical rather than numerical order, because the data type of the key is a string, not an integer.

Figure 12.3. SortedList<> and SortedDictionary<> Class Diagrams

When inserting or removing elements from a sorted dictionary collection, maintenance of order within the collection slightly increases execution time when compared to the straight dictionary classes described earlier. Behaviorally, there are two internal arrays, one for key retrieval and one for index retrieval. On a System.Collections.Sorted sorted list, indexing is supported via the GetByIndex() and SetByIndex() methods. With System.Collections.Generic.SortedList<TKey, TValue>, the Keys and Values properties return IList<TKey> and IList<TValue> instances, respectively. These methods enable the sorted list to behave both as a dictionary and as a list type collection.

Stack Collections: Stack<T> and Stack

Chapter 11 discussed the stack collection classes (see Figure 12.4). The stack collection classes are designed as last in, first out (LIFO) collections. The two key methods are Push() and Pop().

  • Push() places elements into the collection. The elements do not have to be unique.

  • Pop() retrieves and removes elements in the reverse order of how they were added.

To access the elements on the stack without modifying the stack, you use the Peek() and Contains() methods. The Peek() method returns the next element that Pop() will retrieve.

As with most collection classes, you use the Contains() method to determine whether an element exists anywhere in the stack. As with all collections, it is also possible to use a foreach loop to iterate over the elements in a stack. This allows you to access values from anywhere in the stack. Note, however, that accessing a value via the foreach loop does not remove it from the stack. Only Pop() provides this functionality.

Figure 12.4. Stack<T> and Stack Class Diagrams

Queue Collections: Queue<T> and Queue

Queue collection classes, shown in Figure 12.5, are identical to stack collection classes, except they follow the ordering pattern of first in, first out (FIFO). In place of the Pop() and Push() methods are the Enqueue() and Dequeue() methods. The queue collection behaves like a circular array or pipe. You place objects into the queue at one end using the Enqueue() method, and you remove them from the other end using the Dequeue() method. As with stack collection classes, the objects do not have to be unique, and queue collection classes automatically increase in size as required. When data is no longer needed, you recover the capacity using the TRimToSize() method.

Figure 12.5. Queue<T> and Queue Class Diagrams

Linked Lists: LinkedList<T>

In addition, System.Collections.Generic supports a linked list collection that enables both forward and reverse traversal. Figure 12.6 shows the class diagram. Notice there is no corresponding nongeneric type.

Figure 12.6. LinkedList<T> and LinkedListNode<T> Class Diagram

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: