Under System.Collections namespace are the following collections: ArrayList, SortedList, Queue, Stack, Hashtable, BitArray, StringCollection, StringDictionary, ListDictionary, HybridDictionary, and NameValueCollection.
ArrayList is the most basic of all collections. It is a simple resizeable, index-based collections of objects.
|ArrayList arrayList = new ArrayList();
// add individual items
// add multiple items
// insert item at specific position
// insert multiple items at specific position
// using indexer to set specific item
// remove item
// remove first item in ArrayList
// remove first four items in ArrayList
// using Contains(), IndexOf(), and Clear() methods
Iterating Over Items In Collections
To iterate items in a collection such as the ArrayList, you can use either the for loop, IEnumerator interface, or the foreach loop.
|// using for loop
for (int i = 0; i < coll.Count; ++i)
// using IEnumerator interface
// using foreach loop
Interfaces in Collections
.NET supports the following interfaces that are implemented by collections: IEnumerable, ICollection, and IList.
IEnumerable interface is used to provide a common way to iterate over a collection. Its important properties and methods are: Current, MoveNext(), and Reset().
ICollection is derived from IEnumerable and is used to provide a common way to get the items in the collection as well as to copy the collection to an Array object. Its important properties and methods are: Count, and CopyTo().
IList is derived from ICollection and is used to provide a common way to expose lists of items. Its important properties and methods are: Item, Add(), Clear(), Contains(), IndexOf(), Insert(), Remove(), and RemoveAt().
Sorting Items In Collections
To sort items in an ArrayList, you use the Sort() method. The Sort() method uses the Comparer class which is a default implementation that supports the IComparer interface.
To specify an IComparer object to use instead of the default, you use the overloaded Sort() method that takes in an IComparer object.
You can also write your own comparer by implementing the Compare() method of the IComparer interface.
|public class DescendingComparer : IComparer
CaseInsensitiveComparer _comparer = new CaseInsensitiveComparer();
public int Compare(object x, object y)