Using Arrays and Collections
The data types described in previous lessons each hold a single piece of data. A variable might
hold an integer, string, or point in time.
Sometimes it’s convenient to work with a group of related values all at once. For example, sup-
pose you’re the CEO of a huge company that just posted huge losses. In that case, you might want
to give each hourly employee a 10 percent pay cut and give each executive a 15 percent bonus.
In cases like this, it would be handy to be able to store all of the hourly employee data in one
variable so you could easily work with it. Similarly you might like to store the executives’ data
in a second variable so it’s easy to manage.
In this lesson, you learn how to make variables that can hold more than one piece of data. You
learn how to make arrays and different kinds of collections such as
Lists, Dictionaries,
Stacks, and Queues.
This lesson explains how to build these objects and add and remove items from them.
Lesson 19 explains how to get the full benefit of them by looping through them to perform
some action on each of the items they contain.
ARRAYS
An array is a group of values that all have the same data type and that all share the same name.
Your code uses an index, which is an integer greater than or equal to 0, to pick a particular item
in the array.
An array is similar to the mailboxes in an apartment building. The building has a single bank
of mailboxes that all have the same street address (the array’s name). You use the apartment
numbers to pick a particular cubbyhole in the bank of mailboxes.
Figure 16-1 shows an array graphically. This array is named
values. It contains eight entries
with indexes 0 through 7.
16
596906book.indd 195 4/8/10 7:40:02 AM
196
LESSON 16 Using ArrAys And ColleCtions
FIGURE 161
An array’s smallest and largest indexes are called its lower bound and upper
bound. In C#, the lower bound is always 0, and the upper bound is always one
less than the length of the array.
Creating Arrays
The following code shows how you might declare an array of integers. The square brackets indicate an
array so the first part of the statement
int[] means the variable’s data type is an array of integers.
int[] values;
After you declare an array variable, you can assign it to a new uninitialized array. The following
code initializes the variable
values to a new integer array that can hold eight elements:
values = new int[8];
Remember that an array’s lower bound is always 0 in C# so this array has indexes 0 through 7.
As is the case with other variables, you can declare and initialize an array in a single step. The following
code declares and creates the
values array in a single statement:
int[] values = new int[8];
After you have created an array, you can access its members by using the array’s name followed by an
index inside square brackets. For example, the following code initializes the
values array by setting
the Nth entry equal to N squared:
values[0] = 0 * 0;
values[1] = 1 * 1;
values[2] = 2 * 2;
values[3] = 3 * 3;
values[4] = 4 * 4;
values[5] = 5 * 5;
values[6] = 6 * 6;
values[7] = 7 * 7;
Most programmers pronounce values[5] as “values of 5,” “values sub 5,” or
“the 5th element of values.
596906book.indd 196 4/8/10 7:40:02 AM
Arrays
197
After you have placed values in an array, you can read the values using the same square bracket
syntax. The following code displays a message box that uses one of the array’s values:
MessageBox.Show(“7 * 7 is “ + values[7].ToString());
To make initializing arrays easier, C# provides an abbreviated syntax that lets you declare an array
and set its values all in one statement. Simply set the variable equal to the values you want separated
by commas and surrounded by braces as shown in the following code:
int[] values = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 };
A FIBONACCI ARRAY
The Fibonacci program shown in Figure 16-2 (and available
as part of this lesson’s code download) uses an array to dis-
play Fibonacci numbers. Use the
NumericUpDown control to
select a number and click Calculate to see the corresponding
Fibonacci number.
When the user clicks Calculate, the program executes the
following code:
private void calculateButton_Click(object sender, EventArgs e)
{
int[] values = new int[21];
values[0] = 0;
values[1] = 1;
values[2] = values[0] + values[1];
values[3] = values[1] + values[2];
values[4] = values[2] + values[3];
...
values[20] = values[18] + values[19];
int index = (int)numberNumericUpDown.Value;
resultsTextBox.Text = values[index].ToString();
}
The code starts by initializing the values array to hold the first 21 Fibonacci
numbers. It uses the following definition of the numbers to calculate the values:
Fibonacci(i) = Fibonacci(i - 1) + Fibonacci(i - 2)
After initializing the array, the program gets the value selected by the NumericUpDown
control, converts it from a
decimal to an int, uses it as an index into the values
array, and displays the result in
resultTextBox.
FIGURE 162
When you use this syntax, C# uses the number of values you supply to define the array’s size. In
the preceding code, C# would give the
values array 10 entries because that’s how many values the
code supplies.
596906book.indd 197 4/8/10 7:40:03 AM
198
LESSON 16 Using ArrAys And ColleCtions
Multi-Dimensional Arrays
The arrays described in the previous section hold a single row of items but C# also lets you
define multi-dimensional arrays. You can think of these as higher dimensional sequences of
apartment mailboxes.
Figure 16-3 shows a graphic representation of a two-dimensional array with four rows and
eight columns.
FIGURE 163
The following code shows how you could declare, allocate, and initialize this array to hold a
multiplication table with values up to 4 times 7:
int[,] values = new int[5, 7];
values[0, 0] = 0 * 0;
values[0, 1] = 0 * 1;
values[0, 2] = 0 * 2;
...
values[1, 1] = 1 * 1;
values[1, 2] = 1 * 2;
...
values[4, 7] = 4 * 7;
The following code shows the C# syntax for quickly defining and initializing a two-dimensional array:
int[,] cell =
{
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
};
You can use similar syntax to make and initialize higher-dimensional arrays. For example, the
following code makes a four-dimensional array of strings:
string[, , ,] employeeData = new string[10, 20, 30, 40];
596906book.indd 198 4/8/10 7:40:03 AM
Arrays
199
Notice that the denition of the arrays final row ends with a comma. You don’t
need this comma because nothing follows this last row but C# allows you to
include it to give the rows a more uniform format. The commas after the other
rows are required because more rows follow them.
Array Properties and Methods
All arrays have a Length property that your code can use to determine the number of items in the
array. Arrays all have lower bound 0, and for one-dimensional arrays,
Length – 1 gives an array’s
upper bound.
Arrays also have
GetLowerBound and GetUpperBound methods that return the lower and upper
bounds for a particular dimension in an array.
For example, the following code creates a 5-by-10 array. It then displays the lower and upper bounds
for the first dimension. (The dimension numbers start at 0.)
int[,] x = new int[5, 10];
MessageBox.Show(“The first dimension runs from “ +
x.GetLowerBound(0) + “ to “ + x.GetUpperBound(0));
The Array class also provides several useful static methods that you can use to manipulate arrays.
For example, the following code sorts the array named
salaries:
Array.Sort(salaries);
To sort an array, the array must contain things that can be compared in a mean-
ingful way. For example,
int and string data have a natural order, so it’s easy
to say that the string “Jackson” should come before the string “Utah.
If an array holds Employee objects, however, its unclear how you would want to
compare two items. In fact, its likely that you couldn’t dene an order that would
always work because sometimes you might want to sort employees by name and
other times you might want to sort them by employee ID or even salary.
You can solve this problem in a couple of ways including the
IComparer inter-
face (mentioned briefly in Lesson 27s Exercise 2) and making the
Employee
class implement
IComparable (mentioned in Lesson 28). These are slightly more
advanced topics, so they arent covered in great depth here.
The Sort method has many overloaded versions that perform different kinds of sorting. For example,
instead of passing it a single array you can pass it an array of keys and an array of items. In that case the
method sorts the keys, moving the items so they remain matched up with their corresponding keys.
The Table 16-1 summarizes the most useful methods provided by the
Array class.
596906book.indd 199 4/8/10 7:40:03 AM
..................Content has been hidden....................

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