Collecting Data Items
Collecting Data Items
Collectionsclasses used for grouping and managing related objects that allow you to iterate over those objects. Collections take over where arrays end. Arrays are useful, but without the richness of collections most applications would never get off the ground. The .NET Framework supports dealing with data in this way by providing a wide range of collections to store your data in. Types of Collections The .NET Frameworks System.Collections namespace supports several types of collections. These collections are classes that support the gathering of information in an orderly way. Name ArrayList SortedList Queue Stack Hashtable Description A simple resizeable, index-based collection of objects A sorted collection of name/value pairs of objects A first-in, first-out collection of objects A last-in, first-out collection of objects A collection of name/value pairs of objects that allows retrieval by name or index BitArray A compact collection of Boolean values StringCollection A simple resizeable collection of strings StringDictionary A collection of name/values pairs of strings that allows retrieval by name or index ListDictionary An efficient collection to store small lists of objects HybridDictionary A collection that uses a ListDictionary for storage when the number of items in the collection is small, and then migrates the items to a Hashtable for large collections NameValueCollection A collection of name/values pairs of strings that allows retrieval by name or index The ArrayList collection to store and retrieve objects. ArrayList is the most basic of all the collections. Adding and Removing Items The ArrayList class is a simple, unordered container for objects of any type. Adding items to and removing items from the class is very straightforward. ArrayList supports two methods for adding items to the collection: Add and AddRange. The Add method allows you to add a single object to the collection. You can use the Add method to store any object in .NET. Here are s ome examples of code that adds objects of different types to an ArrayList:
// C# ArrayList coll = new ArrayList(); // Add individual items to the collection string s = "Hello"; coll.Add(s); coll.Add("hi"); coll.Add(50); coll.Add(new object()); // C# string[] anArray = new string[] { "more", "or", "less" }; coll.AddRange(anArray); object[] anotherArray = new object[] { new object(), new ArrayList() }; coll.AddRange(anotherArray); The AddRange method supports adding a range of items from any object that supports the ICollection interface (which includes all arrays, ArrayList objects, and most collections discussed in this chapter). The Add and AddRange methods add items to the end of the collection. Because Array-Lists are dynamic collections, they also support inserting objects into them at specific positions. To accomplish this task, an ArrayList also supports the Insert and InsertRange methods. // C# coll.Insert(3, "Hey All"); string[] moreStrings =new string[] { "goodnight", "see ya" }; coll.InsertRange(4, moreStrings); In addition to the Insert and Add methods, you can also use the indexer to set a specific object in the collection, as shown in the following code: // C# Coll[3] = "Hey All"; Note that using the indexer is not the same as using the Insert method, as it sets the item at that specific location in the collection by overwriting the old object at that position rather than just inserting an object. The ArrayList supports removing items from the collection. Three methods Support removing items: Remove, RemoveAt, and RemoveRange. The Remove methodwill remove a specific object from the collection. There is no indication if Remove failed to find the item to remove. In other words, if the
item is not found in the collection, Remove will return without throwing an exception. // C# coll.Add("Hello"); coll.Remove("Hello"); In contrast, the RemoveAt method removes an item at a particular index within the collection. In addition, the RemoveRange method supports removing a range of indexes from the collection all at once. // C# // Removes first item in ArrayList coll.RemoveAt(0); // Removes first four items in ArrayList coll.RemoveRange(0, 4); The ArrayList class also supports some other methods that are useful in adding Objects to and removing objects from the collection: The Clear method is used to empty a collection of all its items. The IndexOf method is used to determine the index of a particular item in the Collection. The Contains method is used to test whether a particular object exists in the Collection. // C# string myString = "My String"; if (coll.Contains(myString)) { int index = coll.IndexOf(myString); coll.RemoveAt(index); } else { coll.Clear(); } Iterating Over Items A collection is not very useful unless you can walk through the items in it. Luckily, the ArrayList (like most collections in this chapter) supports several ways to iterate over its contents. The ArrayList supports a numeric indexer that allows you to write simple code
// C# for (int x = 0; x < coll.Count; ++x) { Console.WriteLine(coll[x]); } By using the ArrayLists Count property and indexer, you can simply walk through the collection. The ArrayList also supports the IEnumerable interface to allow the use of an Enumerator to access the list. The IEnumerable interface dictates that the class supports the GetEnumerator method that returns an IEnumerator interface. In turn, the IEnumerator interface provides a simple interface for iterating in a forward direction. IEnumerator Properties Name Description Current Gets the current item in the collection being enumerated IEnumerator Methods Name Description MoveNext Moves to the next item in the collection. The return value of the method is used to determine whether the enumerator has reached the end of the collection. Reset Sets the enumerator to before the first item in the collection to allow MoveNext to be called to get the first item in the collection. The IEnumerator interface allows you to walk through the list of objects in an ordered way, as seen in this example: // C# IEnumerator enumerator = coll.GetEnumerator(); while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } This example shows the simple pattern of getting an enumerator from the collection and using the MoveNext call to walk through the list. Accessing the Current property from the enumerator returns the current item in the list. By using the foreach construct, you can enumerate a whole list, as the following example shows: // C# foreach (object item in coll) { Console.WriteLine(item);
} The foreach construct specifies that you are enumerating the coll object and creating an item object for each item in the collection. This construct relies on the IEnumerable interface. It can be used on any collection that supports the IEnumerable interface. One of the benefits of this iteration scheme is that if you have a collection of some known types, you can specify the type in the foreach construct to save some time in casting from objects, as you can see in this code snippet: // C# ArrayList newColl = new ArrayList(); newColl.Add("Hello"); newColl.Add("Goodbye"); foreach (string item in newColl) { Console.WriteLine(item); } Sorting Items The ArrayList supports a method to sort a collections items. To sort items within an ArrayList, simply call the Sort method of the ArrayList like so: // C# coll.Sort(); The Sort method works by using the Comparer class to do the comparison. The Comparer class is a default implementation that supports the IComparer interface. This interface dictates that you implement a single method called Compare that takes two objects (for example, a and b) and returns an integer that represents the result of the comparison.
The .NET Framework supports a common interface for how a collections application programming interface (API) should look. This interface is called the ICollection interface, and it derives from the IEnumerable interface. This means that every collection that supports the ICollection interface must also support the IEnumerable interface. The purpose of this interface is to ensure that every collection supports a common way of getting the items in a collection, as well as a way to copy the collection to an Array object. For simple list collections (such as ArrayList), the .NET Framework supports another interface that is used to expose lists of items. This interface is called the IList interface and derives directly from the ICollection interface. If a class supports the IList interface, it must also support the ICollection and IEnumerable interfaces. This consistency of interfaces simplifies the way we work with collections in general.
ICollection Properties
Description Gets the number of items currently in the collection Gets an indicator of whether the collection is thread safe Gets an object that can be used to synchronize the Collection
ICollection Methods
Description Copies the contents of a collection into an Array
Name CopyTo
IList Properties
Description Gets an indicator of whether this collection can be resized Gets an indicator of whether a collection can be changed Gets or sets the item at a specific index in the collection
IList Methods
Description Adds an item to the collection Clears the collections of all items Tests whether a specific item is contained in the collection Finds an item in the collection, and returns the index of the item Adds an item at a specific index in the collection Removes the first occurrence of the specified object in the collection Removes an item at a specific index in the collection