1 How to use arrays and collections Based of Murach’s 2015 Chapter 8,Deitel 2012 Chapter 8 and (19)
2 Objectives Applied Given the specifications for an application that requires the use of a one-dimensional, rectangular, or jagged array, write the code that works with the array. Given the specifications for an application that requires the use of one of the collection classes presented in this chapter, write the code that works with the collection.
3 Objectives (cont.) KnowledgeDistinguish between a for loop and a foreach loop. Explain how the Array class can be used with an array. Distinguish between an untyped and a typed collection class. Describe how the null-conditional operator works and when you would use it. Describe the differences between these collection classes: list, sorted list, queue, stack, and array list.
4 Array class Abstract class defined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays.
5 The syntax for creating a one-dimensional arrayWith two statements type[] arrayName; // declaration statement arrayName = new type[arrayLength]; // assignment statement With one statement type[] arrayName = new type[arrayLength]; Examples that create an array of decimal types decimal[] totals; totals = new decimal[4]; decimal[] totals = new decimal[4]; new Array class All elements initialized to their default values
6 Two arrays in one statement (AVOID it)An array of strings string[] description = new string[3]; Two arrays in one statement (AVOID it) const int MaxCount = 100; decimal[] prices = new decimal[MaxCount], discountPercentages = new decimal[MaxCount];
7 Default values for array elementsstring is a reference type
8 The syntax for referring to an element of an arrayarrayName[index] 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; // would throw 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";
9 The syntax for creating an array and assigning values in one statementtype[] arrayName = [new type[length]] {value1[, value2][, value3]...}; Examples decimal[] totals = new decimal[4] {14.95m, 12.95m, 11.95m, 9.95m}; decimal[] totals = {14.95m, 12.95m, 11.95m, 9.95m}; //automatically sets size string[] names = {"Ted Lewis", "Sue Jones", "Ray Thomas"}; Infer the type of an array from its values var grades = new[] {95, 89, 91, 98}; No []
10 The syntax for creating an array and assigning values in one statement (Details)
11 The syntax for using the Length propertyarrayName.Length 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/4; 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; }
12 Code that displays the numbers array in MessageBoxstring numbersString = ""; for (int i = 0; i < numbers.Length; i++) { numbersString += numbers[i] + " "; } MessageBox.Show(numbersString, "Numbers Test");
13 A for loop that computes the average of the totals arraydecimal sum = 0.0m; for (int i = 0; i < totals.Length; i++) { sum += totals[i]; } decimal average = sum/totals.Length;
14 Code that displays the totals arraystring 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");
15 The syntax of a foreach loop (simpler, but no counter)foreach (type elementName in arrayName) { statements } Code that computes the average of the totals array decimal sum = 0.0m; foreach (decimal total in totals) sum += total; decimal average = sum/totals.Length;
16 Code that displays the numbers arraystring numbersString = ""; foreach (int number in numbers) { numbersString += number + " "; } MessageBox.Show(numbersString, "Numbers Test");
17 Code that displays the totals arraystring totalsString = ""; foreach (decimal total in totals) totalsString += total + "\n"; MessageBox.Show("The totals are:\n" + totalsString + "\n" + "Sum: " + sum + "\n" + "Average: " + average, "Totals Test");
18 The syntax for creating a rectangular array (two-dimensional arrays)type[,] arrayName = new type[rowCount,columnCount]; A statement that creates a 3x2 array int[,] numbers = new int[3,2];
19 2 dimensional array The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-dimensional arrays. A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Ex.:is a 2-dimensional array, which contains 3 rows and 4 columns: Thus, every element in the array a is identified by an element name of the form a[ i,j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.
20 The syntax for referring to an element of a rectangular arrayarrayName[rowIndex, columnIndex] 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;
21 Code that creates a 3x4 array and assigns values with one statementint[,] numbers = { {0,1,2,3}, {4,5,6,7}, 8,6,10,11} }; Code that creates and assigns values to a 3x2 array of ints int [,] a = new int [3,4] { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; column row
22 Code that creates a 3x2 array and assigns values with one statementint[,] numbers = { {1,2}, {3,4}, {5,6} }; Code that creates and assigns values to a 3x2 array of strings string[,] products = {{"CS2015", "Murach's C# 2015"}, {"JAVAPRG", "Murach's Java Programming"}, {"ASP46CS", "Murach's ASP.NET 4.6 with C# 2015"} }; Another way to create the array of strings var products = new[,]
23 The syntax for using the GetLength methodarrayName.GetLength(dimensionIndex) 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]; Description You use the GetLength method to get the number of rows or columns in a rectangular array. To get the number of rows, specify 0 for the dimensionIndex argument. To get the number of columns, specify 1 for this argument. GetLength(1) for one dimensional array yields error
24 Code that displays the numbers arrayint[,] numbers = { {1,2}, {3,4}, {5,6} }; string numbersString = ""; for (int i = 0; i < numbers.GetLength(0); i++) //rows { for (int j = 0; j < numbers.GetLength(1); j++) //columns numbersString += numbers[i,j] + " "; } numbersString += "\n"; MessageBox.Show(numbersString, "Numbers Test");
25 Code that displays the products arraystring[,] products = {{"CS2015", "Murach's C# 2015"}, {"JAVAPRG", "Murach's Java Programming"}, {"ASP46CS", "Murach's ASP.NET 4.6 with C# 2015"} }; 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");
26 The syntax for creating a jagged arrayA jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/arrays/jagged-arrays type[][] arrayName = new type[rowCount][]; Code that creates a jagged array with three rows of different lengths int[][] numbers = new int[3][]; // the number of rows numbers[0] = new int[3]; // the number of columns for row 1 numbers[1] = new int[4]; // the number of columns for row 2 numbers[2] = new int[2]; // the number of columns for row 3
27 The syntax for referring to an element of a jagged arrayarrayName[rowIndex][columnIndex] Code that assigns values to the numbers array int[][] numbers = new int[3][]; numbers[0][0] = 1; numbers[1][0] = 4; numbers[2][0] = 8; numbers[0][1] = 2; numbers[1][1] = 5; numbers[2][1] = 9; numbers[0][2] = 3; numbers[1][2] = 6; numbers[1][3] = 7; Code that creates the numbers array with one statement int[][] numbers = { new int [] {1, 2, 3}, new int [] {4, 5, 6, 7}, new int [] {8, 9} };
28 Jagged Array Console Testpublic static void JaggedArray() { // Declare the array of four elements: int[][] jaggedArray = new int[4][]; // Initialize the elements: jaggedArray[0] = new int[2] { 7, 9 }; jaggedArray[1] = new int[4] { 12, 42, 26, 38 }; jaggedArray[2] = new int[6] { 3, 5, 7, 9, 11, 13 }; jaggedArray[3] = new int[3] { 4, 6, 8 }; // Display the array elements: for (int i = 0; i < jaggedArray.Length; i++) System.Console.Write("Element({0}): ", i + 1); for (int j = 0; j < jaggedArray[i].Length; j++) System.Console.Write(jaggedArray[i][j] + "\t"); } System.Console.WriteLine(); Console.ReadLine();
29 Code that creates a jagged array of stringsstring[][] titles = { new string [3] {"War and Peace", "Wuthering Heights", "1984"}, new string [4] {"Casablanca", "Wizard of Oz", "Star Wars", "Birdy"}, new string [2] {"Blue Suede Shoes", "Yellow Submarine"} }; Another way to create a jagged array of strings var titles = new[] {(new[] {"War and Peace", "Wuthering Heights", "1984"}), (new[] {"Casablanca", "Wizard of Oz", "Star Wars", "Birdy"}), (new[] {"Blue Suede Shoes", "Yellow Submarine"})
30 Code that displays the numbersint[][] numbers = new int[3][]; numbers[0][0] = 1; numbers[1][0] = 4; numbers[2][0] = 8; numbers[0][1] = 2; numbers[1][1] = 5; numbers[2][1] = 9; numbers[0][2] = 3; numbers[1][2] = 6; numbers[1][3] = 7; string numbersString = ""; for (int i = 0; i < numbers.GetLength(0); i++) { for (int j = 0; j < numbers[i].Length; j++) numbersString += numbers[i][j] + " "; } numbersString += "\n"; MessageBox.Show(numbersString, "Jagged Numbers Test");
31 Code that displays the titles arraystring[][] titles = { new string [3] {"War and Peace", "Wuthering Heights", "1984"}, new string [4] {"Casablanca","Wizard of Oz","Star Wars","Birdy"}, new string [2] {"Blue Suede Shoes", "Yellow Submarine"} }; string titlesString = ""; for (int i = 0; i < titles.GetLength(0); i++) { for (int j = 0; j < titles[i].Length; j++) titlesString += titles[i][j] + "|"; titlesString += "\n"; } MessageBox.Show(titlesString, "Jagged Titles Test");
32 Common properties and methods of the Array class
33 Common properties and methods of the Array class
34 Code that uses the GetLength and GetUpperBound methodsint[] numbers = new int[4] {1, 2, 3, 4}; int length = numbers.GetLength(0); // length = 4 int upperBound = numbers.GetUpperBound(0); // upperBound = 3
35 Part 2: Code that uses the Sort methodstring[] lastNames = {"Boehm", "Taylor", "Murach"}; Array.Sort(lastNames); string message = ""; foreach (string lastName in lastNames) message += lastName + "\n"; MessageBox.Show(message, "Sorted Last Names");
36 Code that uses the BinarySearch methodstring[] employees = {"AdamsA", "FinkleP", "LewisJ", "PotterE"}; decimal[] salesAmounts = { m, m, m, m}; int index = Array.BinarySearch(employees, "FinkleP"); decimal salesAmount = salesAmounts[index]; //salesAmount =
37 Code that creates a reference to another array Arrays are created from Arrays class and they a reference types double[] inches1 = new double[3] {1,2,3}; double[] inches2 = inches1; inches2[2] = 4; // changes the third element Console.WriteLine(inches1[2]); //4 Console.WriteLine(inches2[2]); //4 Code that reuses an array variable Arrays cannot change their size, they are immutable inches1 = new double[20]; // make a new array with 20 elements
38 The syntax for copying elements of an arrayArray.Copy(fromArray, toArray, length); 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 the new array values }
39 The syntax for copying selected elements from one array to anotherArray.Copy(fromArray, fromIndex, toArray, toIndex, length); Code that copies some of the elements of an array string[] names = {"Martinez", "Murach", "Boehm"}; string[] lastTwoNames = new string[2]; Array.Copy(names, 1, lastTwoNames, 0, 2); // "Murach", "Boehm"
40 The code for a method that returns an arrayprivate 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);
41 The code for a method that accepts an array argumentprivate 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}; this.ToCentimeters(measurements);
42 The code for a method that uses the params keywordprivate 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 = this.ToCentimeters(1,2,3);
43 A statement that creates a null arraystring[] initials = null; A statement that will throw a NullReferenceException string firstInitial = initials[0].ToUpper();
44 Code that uses if statements to prevent a NullReferenceExceptionif (initials != null) //condition 1 before C# 2015 { if (initials[0] != null) //condition 2 before C# 2015 string firstInitial = initials[0].ToUpper(); } A statement that uses null-conditional operators to prevent a NullReferenceException string firstInitial = initials?[0]?.ToUpper(); A statement that uses a nullable type int? length = initials?.Length;
45 Discussions
46 Part 3. How arrays and collections are similarBoth can store multiple elements, which can be value types or reference types. How arrays and collections are different An array is a feature of the C# language. Collections are classes in the .NET Framework. Collection classes provide methods to perform operations that arrays don’t provide. Arrays are fixed in size. Collections are variable in size.
47 Commonly used collection classes
48 Commonly used collection classes (cont.) (NET 1.0 aand .NET 2.0)
49 The using directive for untyped collectionsusing System.Collections; Code that uses an untyped collection ArrayList numbers = new ArrayList(); numbers.Add(3); numbers.Add(7); numbers.Add("Test"); // will compile - causes runtime error int sum = 0; for (int i = 0; i < numbers.Count; i++) { int number = (int)numbers[i]; // cast is required sum += number; }
50 The using directive for typed collectionsusing System.Collections.Generic; Code that uses a type collection List
51 A list of elements of different typesA list of string elements List
52 Types and untyped colelctions
53 Common properties and methods of the List<> class
54 Common properties and methods of the List<> class (cont.)
55 Code that causes the size of a list of names to be increasedList
56 The syntax for retrieving a value from a listlistName[index] Code that creates a list that holds decimal values List
57 Code that inserts and removes an element from the listList
58 Code that checks for an element in the list and removes it if it existsList
59 SortedList
60 Common properties of the SortedList<> class
61 Common methods of the SortedList<> class
62 Properties of the KeyValuePair
63 How to create and load a sorted listWith separate statements SortedList
64 Code that looks up a value in the sorted list based on a keystring employeeKey = "LewisJ"; decimal salesTotal = salesList[employeeKey]; Code that converts the sorted list to a tab-delimited string (traversing) string salesTableString = ""; foreach (KeyValuePair
65 Part 3. Properties and methods of the Queue<> class
66 Code that uses a queue Queue
67 Properties and methods of the Stack<> class
68 Code that uses a stack Stack
69 Part 4. The syntax for retrieving a value from an array list (untyped)(type) arrayName[index] Code that creates an array list that holds decimal values decimal[] newSalesTotals = { m, m, m, m}; ArrayList salesTotals = new ArrayList(); foreach (decimal d in newSalesTotals) salesTotals.Add(d); Another way to create the array list ArrayList salesTotals = new ArrayList { m, m, m, m }; Code that retrieves the first value from the array list decimal sales1 = (decimal) salesTotals[0]; // sales1 =
70 ArrayList vs List
71 Code that inserts and removes an element from the array listArrayList salesTotals = new ArrayList { m, m, m, m }; salesTotals.Insert(0, m); //insert a new first element decimal sales1 = (decimal) salesTotals[0];// sales1 = decimal sales2 = (decimal) salesTotals[1];// sales2 = salesTotals.RemoveAt(1); // remove the second element sales2 = (decimal) salesTotals[1]; //sales2 =
72 Code that displays the array liststring salesTotalsString = ""; foreach (decimal d in salesTotals) salesTotalsString += d + "\n"; MessageBox.Show(salesTotalsString, "Sales Totals");
73 Code that checks for an element in the array list and removes it if it existsdecimal x = m; if (salesTotals.Contains(x)) salesTotals.Remove(x); Code that sorts and searches the array list salesTotals.Sort(); int sales2Index = salesTotals.BinarySearch(sales2);