Working with Groups of Items

A common scenario in computer programming is managing a group of similar items. For example, you might need to work with a set of values, such as ZIP Codes to which a sales representative is assigned. Alternatively, you might need to work with a group of objects such as the paychecks an employee has received in a given year. When you need to work with a group of elements, you can do so using an array or a collection class. The former is great for working with a set sequential list of items of the same type. The latter is more applicable for managing a variable-sized group of objects.

Arrays

An array is a group of items of the same type (either value or reference types). For instance, you might create an array that contains all integer values or all string values. You also have to define the number of elements contained in your array when you first initialize it. There are ways to expand or contract this size, but these typically involve copying the array into another array. If you need the flexibility of adding and removing items in a group, you want to use a collection class and not an array.

When you define an array’s size, you need to know that they are zero-based arrays. That is, the first element in the array is item zero. Each item is contiguous and sequential. This enables you to set and access items quickly using the items index.


Note

When dimensioning the size of array in C# you get the actual number of items indicated in the definition. Therefore, the declaration short[] myArray = new short[6] yields six items in the array (items 0–5). In Visual Basic, however, a similar call to Dim myArray(6) As Short yields seven items in the array (items 0–6).


The typical array you create is one dimensional, meaning that it contains a single group of indexed items. You declare this type of an array by indicating the number of elements in the array either on the declaration of the variable or before the array’s first use. There are a few valid syntaxes for defining an array. The standard way in C# is to use the new keyword to set the size of the array. In Visual Basic, you can set the size of the array without using the keyword new. The following shows an example.

C#

short[] salesRegionCodes = new short[numRegions];

VB

Dim salesRegionCodes(numRegions) As Short

You access an array through its index value. Array objects inherit for the System.Array class. This gives you a number of properties and methods you can use, including getting the total number of elements in all dimensions of an array (Length) and getting the upper-bound value for a single dimension (GetUpperBound). The following code shows an example of using this last method and accessing an array through its index.

C#

for (int i = 0; i < salesRegionCodes.GetUpperBound(0); i++)
{
  short code = salesRegionCodes[i];
  //additional processing ...
}

VB

For i = 0 To salesRegionCodes.GetUpperBound(0)

  Dim code As Short = salesRegionCodes(i)
  'additional processing ...
Next

You can also initialize the values in an array inside the declaration statement. In this case, the number of elements you define sets the size of the array. The following is an example.

C#

double[] salesFigures = new double[] {12345.98, 236789.86, 67854.12};

VB

Dim salesFigures() As Double = {12345.98, 236789.86, 67854.12}

You can define arrays that have more than a single dimension (up to 32). A common scenario is a two-dimensional array in which one dimension is considered rows and the other columns. You can use the Rank property to determine the number of dimensions in an array.

For an example of a multidimensional array, consider one that contains sales figures for each sales representative (rows) in each region (columns). You might define this array as follows.

C#

double[,] salesByRegion = new double[6, 5];

VB

Dim salesByRegion(6, 5) As Double

Note that an array can also contain other arrays. These type of arrays are called jagged arrays (or arrays of arrays). They are considered jagged because each element in the array might contain an array of different size and dimension; therefore, there might be no real uniformity to the array.

Collection Classes and Generics

A collection class can give you more flexibility when working with objects. For example, you can have objects of different types in a single collection; collections can be of varying lengths; and you can easily add and remove items in a collection.

The standard collection classes are defined inside the System.Collections namespace. The classes in this namespace include a base class for creating your own, custom collections (CollectionBase) and more specific collections such as ArrayList, Stack, SortedList, Queue, and HashTable.

For example, you might create a simple, dynamic ArrayList to contain a set of sales figures. The following code shows how you can create a new ArrayList, add items to it, and loop through those items.

C#

ArrayList salesFigures = new ArrayList();

salesFigures.Add(12345.67);
salesFigures.Add(3424.97);
salesFigures.Add("None");

for (int i = 0; i < salesFigures.Count; i++)
{
  object figure = salesFigures[i];
  //process figures ...
}

VB

Dim salesFigures As New ArrayList()

salesFigures.Add(12345.67)
salesFigures.Add(3424.97)
salesFigures.Add("None")

For i As Integer = 0 To salesFigures.Count - 1
 Dim figure As Object = salesFigures(i)
 'process sales figure data ...
Next

Of course, many additional properties and methods are available to you through the ArrayList and related collection classes. You should explore these for your specific scenarios.

Notice in the preceding code that the collection class has two types of objects inside it: double and string. This can be problematic if you need to rely on a collection of objects all being of the same type. For example, you might want all your sales figures to be of type double; or you might want a collection of only Employee objects. In these cases, you need a strongly typed collection class. You can create these by coding your own, custom collection classes (inheriting from CollectionBase and implementing the interfaces specific to your needs). However, .NET also provides a set of classes called generics that allow for strongly typed groups of objects.

Generic collections can be found inside the System.Collections.Generic namespace. A generic collection class enables you to define the type that the class contains when you initialize it. This then restricts what types the class can contain. You can rely on this information within your code.

You define a generic list in C# using angle brackets (<>) with the type defined inside those brackets. In Visual Basic, you define the generic type inside parenthesis using the Of keyword. For example, the following defines a simple, generic list of items that can only include values of type double.

C#

List<double> salesFigures = new List<double>();

VB

Dim salesFigures As New List(Of Double)

There are many generic collection classes available to you, including Dictionary, HashSet, LinkedList, List, Queue, SortedList, Stack, and more. You can also write your own generic collection classes.

Tuple

The System.Tuple class enables you to create a set, ordered list of items and work with that list. After you’ve created the list, you cannot change it. This makes for easy storage (and access) of sequential items.

For example, if you wanted to create a Tuple to store the month names in the first quarter, you could do so using the static member Tuple.Create. Each item you want to add to the list you add inside parentheses (and separated by commas). You can then access the items in your Tuple using the Item1, Item2, Item3 syntax. Note that the Tuple only exposes item properties for the number of items that exist inside the group. The following code shows an example.

C#

var q1Months = Tuple.Create("Jan", "Feb", "Mar");
string month1 = q1Months.Item1;

VB

Dim q1Months = Tuple.Create("Jan", "Feb", "Mar")
Dim month1 As String = q1Months.Item1

The Tuple class is based on generics. You define the type of object you enable for each member in the list. The Create method shown infers this type for you. However, you might want to be explicit. In this case, you can declare your types using the constructor as follows.

C#

Tuple<int, string, int, string, int, string> q1MonthNumAndName =
        Tuple.Create(1, "Jan", 2, "Feb", 3, "Mar");

VB

Dim q1MonthNumAndName As Tuple(Of Integer, String, Integer, String,
                               Integer, String) =
  Tuple.Create(1, "Jan", 2, "Feb", 3, "Mar")

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

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