Collections are groups of items; in .NET, collections contain objects (including boxed value types). Each object contained in a collection is called an element. Some collections contain a straightforward list of elements, while others (dictionaries) contain a list of key and value pairs. The following collection types consist of a straightforward list of elements: System.Collections.ArrayList System.Collections.BitArray System.Collections.Queue System.Collections.Stack System.Collections.Generic.LinkedList<T> System.Collections.Generic.List<T> System.Collections.Generic.Queue<T> System.Collections.Generic.Stack<T> The following collection types are dictionaries: System.Collections.Hashtable System.Collections.SortedList System.Collections.Generic.Dictionary<T,U> System.Collections.Generic.SortedList<T,U> These collection classes are organized under the System.Collections and the System.Collections.Generic namespaces. In addition to these namespaces, another namespace called System.Collections.Specialized contains a few more useful collection classes. These classes might not be as well known as the previous classes, so here is a short explanation of the collection classes under the System.Collections.Specialized namespace:
The C# compiler also supports a fixed-size array. Arrays of any type may be created using the following syntax: int[] foo = new int[2]; T[] bar = new T[2]; where foo is an integer array containing exactly two elements and bar is an array of unknown type T. Arrays come in several styles as well: multidimensional, jagged, and even multidimensional jagged. Multidimensional arrays are defined as shown here: int[,] foo = new int[2,3]; // A 2-dimensional array // containing 6 elements int[,,] bar = new int[2,3,4]; // A 3-dimensional array // containing 24 elements A two-dimensional array is usually described as a table with rows and columns. The foo array would be described as a table of two rows, each containing three columns of elements. A three-dimensional array can be described as a cube with layers of tables. The bar array could be described as four layers of two rows, each containing three columns of elements. Jagged arrays are arrays of arrays. If you picture a jagged array as a one-dimensional array with each element in that array containing another one-dimensional array, it could have a different number of elements in each row. A jagged array is defined as follows: int[][] baz = new int[2][] {new int[2], new int[3]}; The baz array consists of a one-dimensional array containing two elements. Each of these elements consists of another array, the first array having two elements and the second array having three. The rest of this chapter contains recipes dealing with arrays and the various collection types. |