C#

Chapter 7

Arrays & Collections

Summary

In Chapters7 you will learn how to store lists of data in the arrays and collections. You’ll learn how to perform various actions on these lists using array and collection methods. You will learn about using the ForEach loop with arrays & collections. You will learn about multi-dimensional arrays.

These notes contain some of the highlights of this chapter. You should add any additional notes on the page(s) at the end of this packet. If you run out of space, use loose leaf paper and put them after these pages. Include anything you feel is helpful or important from your work in this chapter.

Up Until Now…

So far, every variable you have declared has only been able to store one value of that type of variable. This has limited your ability to deal with multiple items of the same kind (for example: ten names instead of just one name).

Arrays & Collections allow us to store multiple values of a type of data, or a list.

Let’s explain through an example:

Conside the problem of averaging a set of six scores (of type double). You may represent the variables containing these scores possibly as:

double score0 = 91.0;

double score1 = 87.0;

double score2 = 75.5;

double score3 = 63.0;

double score4 = 52.0;

double score5 = 98.0;

Computing the average of these scores may look like:

double sum = score0+score1+score2+score3+score4+score5;

double average = sum / 6;

Listing each of the 6 scores (or even more involved, asking the user to input each score) is a tedious process. This becomes more tedious as the number of scores needed increases.

Fortunatly you don’t need to name each element separatly. C# provides the array and collection structures to ease this tedious process by allowing you to store a sequence of values using only one identifier (using just one variable name). Below is what an array that would store the six scores looks like. The identifier (or name) of the array variable is “scoreArray”.

double[] scoreArray = {91.0, 87.0, 75.5, 63.0, 52.0, 98.0}

We’ll talk more about the syntax later. For now just realize how much easier it is to use arrays to store lists of the same kind of data versus declaring a different variable for each item in the list. You may also realize that we can probably use a loop to sum the scores in the array (and do other operations against the array), we’ll look more into this later.

Arrays vs. Collections (List)

We will be looking specifically at two classes to store lists of data:

1) Array class2) Lists (a member of the collections class)

ARRAYS / COLLECTIONS
COMMON CHARACTERISTICS / They contain multiple values of data of the same type (all int’s, all doubles, all strings, …)
Each can contain elements of only one type. You must specify the type in your code. After you declare the type, it can’t change. (See Fig. 1)
Each element in the array/collection is accessed by an index, which is just a number that indicates the position or slot where the value is stored in the array/collection. The first element of your array or collection is always indexed by 0.
You can access them both with the syntax using square brackets to specify an index:
  • myList[3]
Both have methods & properties (although they are different) that are used to perform various actions on them.
The name you give it should be a singular noun (“score” not “scores”, “lastName” not “lastNames”)
Size of Array / Collection (how many Elements does it have? What is its Dimensions?) / The size of your array must be decided when the array is created. You must use an integer to specifiy this value. This is also called the length of the array. This cannot be changed. / The size of a collection is never decided. It grows as you add items and shrinks as you remove items.
Manpulating Data / Difficult to move, add, delete data in an array. / Easy to move, add, delete data in a collection.
Multi-Dimensional Storage / You can create multi-dimensional arrays (i.e. – a “2 by 2” (2D) array would be like a spreadsheet with 2 rows and 2 columns; a “3 by 3” (3D) array would look like a Rubik’s Cube. / Not available.
When to Use / When you know the size of your array.
When you need multi-dimensional storage. / When the size of the storage needed is not known and may grow / shrink.
SYNTAX
Declaring
Arrays / type[ ] variableName = newtype[length - integerValue];
Example: double[ ] myArray = newdouble[6];
This creates an array called ‘myArray’ that has an length of six (it can hold 6 different values).
Collections (List) / Listtype> variableName = newListtype>();
Example: Listint> intList = newListint>();
This creates a List with no values. You would then use the Collection methods to add values to this List.
Declaring & Initializing
Arrays / type[ ] variableName = {value1, value2, … valueN};
Example: double[ ] myArray = {5.0, 6.3, 7.5, 9.0, 15.0, 17.0};
This creates an array called ‘myArray’ and puts six values in the array. This makes the length/size/dimension of the array equal to six. The length is implicitly taken from the number of values you entered; so you don’t have to explicitly state the length.
Collections (List) / Listtype> variableName = newListtype{value1, value2, …valueN};
Example: Listint> intList = newListint {2, 5, 7, 9, 11};
This creates a List and puts fivevalues in it. Note the curly-braces contain the values.
Assigning
Arrays or Collections / arrayName [index] = value;
Example: myArray [4] = 75;
This assigns the value of ‘75’ in the array variable ‘myArray’ in its 4th index.
arrayName = otherArray;
This sets the entire array called ‘arrayName’ equal to the array called ‘otherArray’ (see text p. 352 Ex. 7-13)
Accessing
Arrays or Collections / variableName[index - integerValue]
Remember the index starts at ZERO. So if the array length is 5, your indices range from 0-4.
Finding the Length
Arrays / myArray.Length  returns an integer value representing the size of the array
Collections / intList.Count returns an integer value representing the size of the collection


More on Arrays & Collections(List Class)

Arrays & collections are very useful for holding lots of values under the same name. As you may have already realized, collections do all the things that arrays do but have some extra features that make them more powerful than arrays.

Collections make it easier to do things like sorting the data in your lists, deleting items, and adding more items. The collection class contains many sub-classes that store lists of objects in different ways. In this course we will only be working with the collection class called Lists.

You use a List when your collection may need items added to it, deleted from it, or needs to be sorted. For example, suppose you are teacher with a class of ten children. You could keep a list of the children's names, add new students, delete ones who leave, and even sort them into highest to lowest grades. If you used a normal array, it would be difficult to do these things.

(Note: your textbook discusses the ArrayListclas and not Listclasses. This functionality is available; however it is outdated and has been replaced by the List class. The List class allows for more secure programming and in most cases faster processing when working with the list of data. For these reasons we will use the List class and NOT the ArrayListclass.

Simple Program:

Create and initialize an array that contains 5 scores.

Create and initialize a List with 3 names.

Write the first score to the screen.

Write the first name to the screen.

int[] scoreArray = { 20, 40, 60, 80, 100 };

Liststring> nameList = newListstring> { "John", "Mike", "Sue" };

Console.WriteLine("The first score is {0}", scoreArray[0]);

Console.WriteLine("The first name is {0}", nameList[0]);

//Wait for user to acknowledge the results.

Console.WriteLine("");

Console.WriteLine("Press any key to end program...");

Console.ReadKey();

Using a Loop to Have a User Input Data Into an Array/Collection

Now that we know the usefulness of arrays & collections, let’s see how we can use a For loop to have the user enter values into our array/collection.

//Using a FOR Loop to have a user enter 4 integers into an array

int[] numberArray = newint[4];

for (int i = 0; i < numberArray.Length; i++)

{

numberArray[i] = Ask4Information("an integer");

}

What would you use if you and the user didn’t know how many values they are going to enter (you don’t know how the length of the array/list needs to be)?

(p. 340 shows how to write a sentinal-controlled loop to resolve this issue using an array with a Length that is so large that the intent is that it is never reacher. A better solution is to use a List (Collection) and the propper methods for adding elements to the List, instead of creating a excessively large array.)

Common Array/Collection Error

When you loop through an array/collection you may loop one value too sort or one too many (due to your counting error). If you are one value too short, no error is displayed (since its OK only to loop through some of the array/collection). If you are one value too many than you will receive the following error when you execute the program: “IndexOutOfRangeException” and “Index was outside the bounds of the array”.

Using a Foreach Loop with Arrays & Collections

If you need to iterate through the entire array/collection you can use the foreach loop (it will prevent the potential error discussed in the previous section). However, it can be used to READ elements only (no write access); it can not change any contents. It always goes through the entire array/collection (all elements). The syntax is as follows:

foreach (typename in arrayName)

{

}

Where…

type is the type of the array

arrayName is the name of the array/collection you are reading values from

name is the name of the variable where you are going to store the value from the array/collection.

The sample code below shows how to use a foreach loop to loop through all the elements in an array so we can sum the scores of all values in the array.

int[] scoreArray = { 20, 40, 60, 80, 100 };

int sum=0;

double average=0;

foreach (int score in scoreArray)

{

sum = sum + score;

}

average = (double)sum / scoreArray.Length;

Class Methods

We mentioned earlier that both the Array class and the List class have methods that can perform various tasks on the data stored in these lists. The chart below looks at a few of these methods for each of these classes. Refer to the text and the online docs for a more complete list.

ARRAY METHODS / For the examples, let the Array be:
double[ ] waterDepth={2.4, 3.5, 6.8};
Method / Description / Example
Clear (arrayName, <int starting index>, <int how many do you want to count> / Sets elements in array to zero, false or null reference. / Array.Clear (waterDepth, 1, 1)
Sets the element in index 1 to zero.
Clone() / Creates a copy of the array. / object p = waterDepth.Clone();
depthClone = (double[]) p;
Clones the waterDepth array as an object, then casts the object to an array.
Reverse(arrayName) / Reverses the order of the elements in the specified array. / Array.Reverse (waterDepth)
GetValue(int index) / Returns the value of the element at the specified index. / waterDepth.GetValue(2)
This would return ‘6.8’.
IndexOf(arrayName, valueYouAreSearchingFor) / Returns the index of the first occurrence of the value specified. / int I = Array.IndexOf (waterDepth, 3.5);
Returns a ‘1’.
Sort(arrayName) / Sorts the elements in your array. / Array.Sort (waterDepth);
Play with this to see how it sorts various types.
Copy(arrayNameFrom, startingIndex, arrayNameTo, startingIndexInToArray, <int how many do you want to copy> / Copies a section of one array to another array. / Array.Copy (waterDepth, 0, depthCopy, 0, 2)
This copies the first 2 elements of the waterDepth array into the first 2 elements of the depthCopy array.
LIST METHODS / For the examples, let the List be:
Listdouble> waterDepth = newListdouble>{2.4, 3.5, 6.8};
Method / Description / Example
Add
<list>.Add(value) / Adds a value onto the end of the List / waterDepth.Add(7.6);
Adds ‘7.6’ to the end of the list.
ToArray
<newArray> = <listToCopy>.ToArray() / Copies the elements to a new Array (not List) / newArray =waterDepth.ToArray();
IndexOf
<list>.IndexOf(value) / Returns the index of the first occurrence of the value specified. / waterDepth.IndexOf (2.4);
Returns a ‘0’.
Contains
<list>.Contians(value) / Determines whether an element is in the List. You need to figure out what it returns??? / waterDepth.Contains(value);
Sort
<list>.Sort( ) / Sorts your elements in the List. / waterDepth.Sort()
Reverse
<list>.Reverse( ) / Reverses the elements in the List. / waterDepth.Reverse()
Remove
<list>.Remove(value) / Removes the first occurrence of the specified object. / waterDepth.Remove(3.5);
Removes 3.5 from the List.
RemoveAt
<list>.RemoveAt(value) / Removes the element at the specified index. / waterDepth.RemoveAt(2);
Removes ‘6.8’ from the list.
Insert
<list>.Insert(index, value) / Inserts an element at the specified index. / waterDepth.Insert(0,15.4);
Inserts “15.4” at the index of zero.

Using Arrays as Parameters when Calling Your Methods

Recall your Ch 4 notes on writing your own class methods. Review these before continuing.

Calling a Class Method and passing an array variable to it

Same as we learned in chapter 4. Just put the array variable in the argument list (no square brackets are needed)

Class Method Heading:

same as what we learned in chapter 4, the only difference is that the argument is an array whose syntax is shown below. Notice that the array size is not defined, this allows the array to take the size of the array that is being passed to it (just make sure the types are the same).

modifiersreturntypeMethodName> (type[ ] arrayName, …)

****Arrays are reference variables. Therefore when you pass an array to a method, by default, you pass a reference to the address of the array elements. The importance of this feature is that if the method changes the array, the changes are made to the actual data.

REVIEW TEXT P. 348 EXAMPLE 7-12

Using ‘params’ in your Argument list:

It allows a variable number of arguments to be passed to the method.

If you include the ‘params’ argument in the method heading, the array identifier it is used with must be the last parameter listed in the method heading.

Example: (excerpt from text p. 353 Ex. 7-14)

Calling the method:

DisplayItems(1, 2, 3, 4);

DisplayItems(1500, anArray[1] * anArray[2]);

Method Heading

Public static void DisplayItems(params int[ ] item)

Two-Dimensional (2-D) Arrays

Think of a 2-D array as a spreadsheet with ‘m’ rows and ‘n’ columns. The total number of elements would then be ‘m times n’ and each element would hold a value.

Declare:

type [ , ] arrayName = newtype [ m-1 , n-1 ]

  • the ‘m-1’ & ‘n-1’ is because remember these are indices; and each index starts with ZERO not one.

Declare & Initialize:

type [ , ] arrayName = { { value(1,1), …, value(1,m-1)}, …{value(m-1,1), …, value(m-1,n-1)} }

  • Notice that when adding values you add across each row before going down to the next column.

Using the Length property:

This returns the total number of elements in all dimensions (m times n)

Using the GetLength method:

GetLength(0) returns the number of rows

GetLength(1) returns the number of columns

Using the Foreach Loop:

It loops through all the elements in row 0, then row 1, and continues this until it finishes with row m.

Ch 7 Skip:

Arrays in Classes (skip until Instance methods are learned)

Jagged Arrays

YOUR CHAPTER 7NOTES

In this space write any important notes that you have learned from answering the chapter exercises, writing the programming exercises, from the Quick Review, or from any class discussions.

YOUR CHAPTER 7NOTES (continued)

In this space write any important notes that you have learned from answering the chapter exercises, writing the programming exercises, form the Quick Review, or from any class discussions.

Page 1 of 14