2/19/2024
How to use arrays
and collections
C8, Slide 1
Objectives
Applied
1. Given the specifications for an app that requires the use of a one-
dimensional or rectangular array, write the code that works with
the array.
2. Given the specifications for an app that requires the use of one of
the collection classes presented in this chapter, write the code that
works with the collection.
C8, Slide 2
1
2/19/2024
Objectives (continued)
Knowledge
1. Distinguish between a for loop and a foreach loop.
2. Explain how the Array class can be used with an array.
3. Describe how the null-conditional operator works and when you
would use it.
4. Describe how you use a list pattern to match a sequence of patterns
against the elements in an array or list.
5. Distinguish between an untyped and a typed collection class.
6. Describe the differences between these collection classes: list,
sorted list, queue, stack, and array list.
C8, Slide 3
Examples that create an array of decimal types
With two statements
decimal[] totals;
totals = new decimal[4];
With one statement
decimal[] totals = new decimal[4];
C8, Slide 4
2
2/19/2024
An array of strings
string[] description = new string[3];
C8, Slide 5
Two arrays in one statement
const int MaxCount = 100;
decimal[] prices = new decimal[MaxCount],
discountPercentages = new decimal[MaxCount];
C8, Slide 6
3
2/19/2024
Assign values by accessing each element
Code that assigns values to an array of decimal types
decimal[] totals = new decimal[4];
totals[0] = 14.95m;
totals[1] = 12.95m;
totals[2] = 11.95m;
totals[3] = 9.95m;
//totals[4] = 8.95m; // an IndexOutOfRangeException
Code that assigns objects to an array of strings
string[] names = new string[3];
names[0] = "Ted Lewis";
names[1] = "Sue Jones";
names[2] = "Ray Thomas";
C8, Slide 7
Examples that create an array and assign values
in one statement
decimal[] totals =
new decimal[4] {14.95m, 12.95m, 11.95m, 9.95m};
decimal[] totals = {14.95m, 12.95m, 11.95m, 9.95m};
string[] names = {"Ted Lewis", "Sue Jones", "Ray Thomas"};
C8, Slide 8
4
2/19/2024
Infer the type of an array from its values
var grades = new[] {95, 89, 91, 98};
C8, Slide 9
Code that computes the average
of an array of totals
decimal[] totals = {14.95m, 12.95m, 11.95m, 9.95m};
decimal sum =
totals[0] + totals[1] + totals[2] + totals[3];
decimal average = sum/totals.Length;
C8, Slide 10
10
5
2/19/2024
Code that puts the numbers 0 through 9
into an array
int[] numbers = new int[10];
for (int i = 0; i < numbers.Length; i++)
numbers[i] = i;
C8, Slide 11
11
Code that uses a for loop
to display the numbers array
string numbersString = "";
for (int i = 0; i < numbers.Length; i++)
numbersString += numbers[i] + " ";
MessageBox.Show(numbersString, "Numbers Test");
C8, Slide 12
12
6
2/19/2024
A for loop that computes the average
of the totals array
decimal sum = 0.0m;
for (int i = 0; i < totals.Length; i++)
sum += totals[i];
decimal average = sum/totals.Length;
C8, Slide 13
13
Code that uses a for loop
to display the totals array
string totalsString = "";
for (int i = 0; i < totals.Length; i++)
totalsString += totals[i] + "\n";
MessageBox.Show("The totals are:\n" +
totalsString + "\n" +
"Sum: " + sum + "\n" +
"Average: " + average, "Totals Test");
C8, Slide 14
14
7
2/19/2024
Code that uses a foreach loop
to display the numbers array
string numbersString = "";
foreach (int number in numbers)
{
numbersString += number + " ";
}
MessageBox.Show(numbersString, "Numbers Test");
C8, Slide 15
15
Code that uses a foreach loop
to compute the average of the totals array
decimal sum = 0.0m;
foreach (decimal total in totals)
sum += total;
decimal average = sum/totals.Length;
C8, Slide 16
16
8
2/19/2024
Code that uses a foreach loop
to display the totals array
string totalsString = "";
foreach (decimal total in totals)
totalsString += total + "\n";
MessageBox.Show("The totals are:\n" +
totalsString + "\n" +
"Sum: " + sum + "\n" +
"Average: " + average,
"Totals Test");
C8, Slide 17
17
About arrays
A statement that creates a 3x2 array
int[,] numbers = new int[3,2];
The index values for the elements
of a 4x4 rectangular array
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
3,0 3,1 3,2 3,3
Code that assigns values to the numbers array
numbers[0,0] = 1;
numbers[0,1] = 2;
numbers[1,0] = 3;
numbers[1,1] = 4;
numbers[2,0] = 5;
numbers[2,1] = 6;
C8, Slide 18
18
9
2/19/2024
Array examples
Code that creates a 3x2 array
and assigns values with one statement
int[,] numbers = { {1,2}, {3,4}, {5,6} };
Code that creates and assigns values
to a 3x2 array of strings
string[,] products =
{{"C#", "Murach's C#"},
{"JAVA", "Murach's Java Programming"},
{"ASPMVC", "Murach's ASP.NET MVC"}};
Another way to create the array of strings
var products = new[,]
{{"C#", "Murach's C#"},
{"JAVA", "Murach's Java Programming"},
{"ASPMVC", "Murach's ASP.NET MVC"}};
C8, Slide 19
19
Code that works with the numbers array
int numberOfRows = numbers.GetLength(0);
int numberOfColumns = numbers.GetLength(1);
int sumOfFirstRow = numbers[0,0] + numbers[0,1];
C8, Slide 20
20
10
2/19/2024
Code that displays the rectangular numbers array
string numbersString = "";
for (int i = 0; i < numbers.GetLength(0); i++)
{
for (int j = 0; j < numbers.GetLength(1); j++)
numbersString += numbers[i,j] + " ";
numbersString += "\n";
}
MessageBox.Show(numbersString, "Numbers Test");
C8, Slide 21
21
Code that displays the rectangular products array
string productsString = "";
for (int i = 0; i < products.GetLength(0); i++)
{
for (int j = 0; j < products.GetLength(1); j++)
productsString += products[i,j] + "\t\t";
productsString += "\n";
}
MessageBox.Show(productsString, "Products Test");
C8, Slide 22
22
11
2/19/2024
Statements that use the GetLength()
and GetUpperBound() methods
int[] numbers = new int[4] {1, 2, 3, 4};
int length = numbers.GetLength(0);
int upperBound = numbers.GetUpperBound(0);
C8, Slide 23
23
Code that uses the Sort() method
string[] lastNames = {"Boehm", "Taylor", "Murach"};
Array.Sort(lastNames);
string message = "";
foreach (string lastName in lastNames)
message += lastName + "\n";
MessageBox.Show(message, "Sorted Last Names");
C8, Slide 24
24
12
2/19/2024
Code that uses the BinarySearch() method
string[] employees =
{"AdamsA", "FinkleP", "LewisJ", "PotterE"};
decimal[] salesAmounts =
{3275.68m, 4298.55m, 5289.57m, 1933.98m};
int index = Array.BinarySearch(employees, "FinkleP");
decimal salesAmount = salesAmounts[index];
// salesAmount = 4298.55
C8, Slide 25
25
Code that creates a reference to another array
double[] inches1 = new double[3] {1,2,3};
double[] inches2 = inches1;
inches2[2] = 4; // changes the third element
C8, Slide 26
26
13
2/19/2024
Code that reuses an array variable
inches1 = new double[20];
C8, Slide 27
27
Code that copies all the elements of an array
double[] inches = new double[3] {1,2,3};
double[] centimeters = new double[3];
Array.Copy(inches, centimeters, inches.Length);
for (int i = 0; i < centimeters.Length; i++)
centimeters[i] *= 2.54; // set new values
C8, Slide 28
28
14
2/19/2024
Code that copies some of the elements of an array
string[] names = {"Murach", "Boehm", "Delamater"};
string[] lastTwoNames = new string[2];
Array.Copy(names, 1, lastTwoNames, 0, 2);
C8, Slide 29
29
The code for a method that returns an array
private decimal[] GetRateArray(int elementCount)
{
decimal[] rates = new decimal[elementCount];
for (int i = 0; i < rates.Length; i++)
rates[i] = (decimal) (i + 1) / 100;
return rates;
}
A statement that calls the method
decimal[] rates = this.GetRateArray(4);
C8, Slide 30
30
15
2/19/2024
A method that accepts an array argument
private void ToCentimeters(double[] measurements)
{
for (int i = 0; i < measurements.Length; i++)
measurements[i] *= 2.54;
}
Statements that declare the array
and call the method
double[] measurements = {1,2,3};
ToCentimeters(measurements);
C8, Slide 31
31
A method that returns an array
private double[] ToCentimeters(
params double[] measurements)
{
for (int i = 0; i < measurements.Length; i++)
measurements[i] *= 2.54;
return measurements;
}
A statement that calls the method
double[] measurements = ToCentimeters(1,2,3);
C8, Slide 32
32
16
2/19/2024
A statement that creates a null array
string[] initials = null;
A statement that throws NullReferenceException
string firstInitial = initials[0].ToUpper();
C8, Slide 33
33
Code that uses if statements
to prevent a NullReferenceException
if (initials != null)
{
if (initials[0] != null)
{
string firstInitial = initials[0].ToUpper();
}
}
C8, Slide 34
34
17
2/19/2024
A statement that uses null-conditional operators
to prevent a NullReferenceException
string? firstInitial = initials?[0]?.ToUpper();
C8, Slide 35
35
The array that’s used in the examples that follow
decimal[] sales =
{ 22125.67m, 25362.35m, 21478.93m, 27495.72m,
26405.61m, 19476.29m, 31837.56m, 28649.01m };
How to refer to an element from the end
of an array
decimal previousMonthSales = sales[^2]; // 31837.56
C8, Slide 36
36
18
2/19/2024
How to refer to a range of elements
By including starting and ending indexes
var firstQtrSales = sales[0..3]; // indexes 0 through 2
By including just an ending index
var firstQtrSales = sales[..3]; // indexes 0 through 2
By including just a starting index
var secondHalfSales = sales[6..]; // indexes 6 through 7
By including no starting or ending index
var YTDSales = sales[..]; // indexes 0 through 7
By including an index from the end of the array
var secondQtrSales = sales[3..^2];
// indexes 3 through 5
C8, Slide 37
37
How to use a range in a foreach loop
totalSales = 0.0m;
foreach (decimal sale in sales[3..6])
{
totalSales += sale;
}
C8, Slide 38
38
19
2/19/2024
How to use the Index and Range types
(.NET Core 3.0 and later)
Index previousMonthIndex = ^2;
decimal previousMonthSales =
sales[previousMonthIndex]; // 31837.56
Range secondQtrRange = 3..6;
var secondQtrSales = sales[secondQtrRange];
// indexes 3 through 5
C8, Slide 39
39
The list used by the List patterns
int[] quantity = { 100, 200, 300, 400 };
List patterns that test the values
if (quantity is [100, 200, 300, 400]) // true
if (quantity is [100, 200, 400, 400]) // false
if (quantity is [100, 200, 300]) // false
if (quantity is [100, 200, 300, _]) // true
if (quantity is
[< 200, 200 or 300, >= 300 and < 400, > 200])
// true
C8, Slide 40
40
20
2/19/2024
Slice patterns within list patterns
if (quantity is [100, 200, ..]) // true
if (quantity is [.., 400]) // true
if (quantity is [> 0, .., > 500]) // false
C8, Slide 41
41
A var pattern within a list pattern
if (quantity is [100, 200, 300, var fourth])
// true
C8, Slide 42
42
21
2/19/2024
A switch expression that uses list patterns
int index = quantity switch
{
[> 0, > 0, > 0, > 0] => -1,
[> 0, > 0, > 0, <= 0] => 3,
[> 0, > 0, <= 0, ..] => 2,
[> 0, <= 0, ..] => 1,
_ => 0
};
C8, Slide 43
43
Arrays vs. collections
Similarities
Both can store multiple elements, which can be value types or
reference types.
Differences
An array is a feature of the C# language. Collections are .NET
classes.
Collection classes provide methods to perform operations that
arrays don’t provide.
Arrays are fixed in size. Collections are variable in size.
C8, Slide 44
44
22
2/19/2024
The using directive for untyped collections
using System.Collections;
Code that uses an untyped collection
ArrayList numbers = new ArrayList();
numbers.Add(3);
numbers.Add(7);
numbers.Add("Test"); // will compile--runtime error
int sum = 0;
for (int i = 0; i < numbers.Count; i++)
{
int number = (int)numbers[i]; // cast is required
sum += number;
}
C8, Slide 45
45
The using directive for typed collections
using System.Collections.Generic;
Code that uses a typed collection
List<int> numbers = new List<int>();
numbers.Add(3);
numbers.Add(7);
//numbers.Add("Test"); // won't compile
int sum = 0;
for (int i = 0; i < numbers.Count; i++)
{
int number = numbers[i]; // no cast needed
sum += number;
}
C8, Slide 46
46
23
2/19/2024
Lists
A list of string elements
List<string> titles = new List<string>();
A list of decimal elements
List<decimal> prices = new List<decimal>();
A list of strings with a capacity of 3
List<string> lastNames = new List<string>(3);
C8, Slide 47
47
Code that causes the size of a list of names
to be increased
List<string> lastNames = new List<string>(3);
lastNames.Add("Boehm");
lastNames.Add("Delamater");
lastNames.Add("Murach");
lastNames.Add("Taylor"); //Capacity is doubled
lastNames.Add("Baylon");
lastNames.Add("McCoy");
lastNames.Add("Slivkoff"); //Capacity is doubled
C8, Slide 48
48
24
2/19/2024
Code that creates a list that holds decimal values
List<decimal> salesTotals = new List<decimal>
{ 3275.68m, 4398.55m, 5289.75m, 1933.98m };
Code that retrieves the first value from the list
decimal sales1 = salesTotals[0];
// sales1 = 3275.68
C8, Slide 49
49
Code that inserts and removes an element
salesTotals.Insert(0, 2745.73m);
// insert new first element
sales1 = salesTotals[0]; // sales1 = 2745.73
decimal sales2 = salesTotals[1]; // sales2 = 3275.68
salesTotals.RemoveAt(1); // remove second element
sales2 = salesTotals[1]; // sales2 = 4398.55
C8, Slide 50
50
25
2/19/2024
Code that displays the list in a dialog
string salesTotalsString = "";
foreach (decimal d in salesTotals)
salesTotalsString += d.ToString() + "\n";
MessageBox.Show(salesTotalsString, "Sales Totals");
C8, Slide 51
51
Code that checks for an element in the list
and removes it if it exists
decimal x = 2745.73m;
if (salesTotals.Contains(x))
salesTotals.Remove(x);
C8, Slide 52
52
26
2/19/2024
Code that sorts and searches the list
salesTotals.Sort();
int sales2Index = salesTotals.BinarySearch(sales2);
C8, Slide 53
53
How to create and load a sorted list
with separate statements
SortedList<string, decimal> salesList =
new SortedList<string, decimal>(4);
salesList.Add("FinkleP", 4398.55m);
salesList.Add("AdamsA", 3275.68m);
salesList.Add("PotterE", 1933.98m);
salesList.Add("LewisJ", 5289.75m);
C8, Slide 54
54
27
2/19/2024
How to create and load a sorted list
with a collection initializer
SortedList<string, decimal> salesList =
new SortedList<string, decimal>
{ { "FinkleP", 4398.55m }, { "AdamsA", 3275.68m },
{ "PotterE", 1933.98m }, { "LewisJ", 5289.75m } };
C8, Slide 55
55
How to create and load a sorted list with
an index initializer inside a collection initializer
SortedList<string, decimal> salesList =
new SortedList<string, decimal>
{ ["FinkleP"] = 4398.55m, ["AdamsA"] = 3275.68m,
["PotterE"] = 1933.98m, ["LewisJ"] = 5289.75m };
C8, Slide 56
56
28
2/19/2024
Code that looks up a value in the sorted list
based on a key
string employeeKey = "LewisJ";
decimal salesTotal = salesList[employeeKey];
C8, Slide 57
57
Code that converts the sorted list
to a tab-delimited string
string salesTableString = "";
foreach (KeyValuePair<string, decimal> employeeSalesEntry
in salesList)
{
salesTableString += employeeSalesEntry.Key + "\t"
+ employeeSalesEntry.Value + "\n";
}
MessageBox.Show(salesTableString,"Employee Sales Totals");
C8, Slide 58
58
29
2/19/2024
Code that uses a queue
Queue<string> nameQueue = new Queue<string>();
nameQueue.Enqueue("Boehm");
nameQueue.Enqueue("Taylor");
nameQueue.Enqueue("Murach");
string nameQueueString = "";
while (nameQueue.Count > 0)
nameQueueString += nameQueue.Dequeue() + "\n";
MessageBox.Show(nameQueueString, "Queue");
C8, Slide 59
59
Code that uses a stack
Stack<string> nameStack = new Stack<string>();
nameStack.Push("Boehm");
nameStack.Push("Taylor");
nameStack.Push("Murach");
string nameStackString = "";
while (nameStack.Count > 0)
nameStackString += nameStack.Pop() + "\n";
MessageBox.Show(nameStackString, "Stack");
C8, Slide 60
60
30
2/19/2024
Code that creates an array list
that holds decimal values
decimal[] newSalesTotals =
{3275.68m, 4398.55m, 5289.75m, 1933.98m};
ArrayList salesTotals = new ArrayList();
foreach (decimal d in newSalesTotals)
salesTotals.Add(d);
Another way to create the array list
ArrayList salesTotals = new ArrayList
{ 3275.68m, 4398.55m, 5289.75m, 1933.98m };
Code that retrieves the first value
from the array list
decimal sales1 =
(decimal) salesTotals[0]; // sales1 = 3275.68
C8, Slide 61
61
Code that inserts and removes an element
from the array list
salesTotals.Insert(0, 2745.73m);
// insert a new first element
sales1 = (decimal) salesTotals[0];
// sales1 = 2745.73
decimal sales2 = (decimal) salesTotals[1];
// sales2 = 3275.68
salesTotals.RemoveAt(1); // remove the second element
sales2 = (decimal) salesTotals[1];
// sales2 = 4398.55
C8, Slide 62
62
31
2/19/2024
Code that works with the salesTotals array list
Code that displays the array list in a dialog
string salesTotalsString = "";
foreach (decimal d in salesTotals)
salesTotalsString += d + "\n";
MessageBox.Show(salesTotalsString, "Sales Totals");
Code that checks for an element in the array list and
removes it if it exists
decimal x = 2745.73m;
if (salesTotals.Contains(x))
salesTotals.Remove(x);
Code that sorts and searches the array list
salesTotals.Sort();
int sales2Index = salesTotals.BinarySearch(sales2);
C8, Slide 63
63
32