1 / 67

Working With C# Arrays And .NET Lists

Working With C# Arrays And .NET Lists. Lecture Overview. Discuss arrays Discuss the various types of lists available through C # and the .NET Framework. Arrays (Introduction). Arrays store repeating data items having the same data type Arrays have one or more dimensions

gomer
Download Presentation

Working With C# Arrays And .NET Lists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Working With C# Arrays And .NET Lists

  2. Lecture Overview • Discuss arrays • Discuss the various types of lists available through C# and the .NET Framework

  3. Arrays (Introduction) • Arrays store repeating data items having the same data type • Arrays have one or more dimensions • The number of dimensions is called the rank • Think of a one-dimensional array as a list or vector • And a two-dimensional array as a table or grid • And a three-dimensional array as a cube

  4. Arrays (Introduction 2) • Arrays are reference types • Memory is allocated from the managed heap • Uninitialized arrays will throw null reference exceptions if you try to use them • Test whether an array references null if (DemoArray1 == null) { // It’s a null pointer. }

  5. Arrays (Introduction 3) • Arrays (almost always) have a lower bound (smallest subscript) of 0 • We can trick .NET to create non-zero-based arrays but DON’T DO IT • ReDim (Visual Basic) statement changes the size of an array while an application is running • It’s not supported in C# • We need to use Array.CopyToRefer to frmMain.btnCopyArray_Click

  6. Declaring Arrays (Introduction) • The process is conceptually similar to VB • The syntax varies considerably though • The public and private access modifiers apply as usual • The [] characters follow the data type to denote that the variable is an array • The array name follows the data type • Example to declare an uninitialized array: private int[] demo;

  7. Declaring 1D Arrays • Declare a one-dimensional array with no initial elements private int[] Alist; • Declare a one-dimensional array with 3 elements (subscripts values are 0 through 2) private int[] Alist = new int[3]; • Declare a one-dimensional array and initialize it private int[] Alist = new int[] {1, 2, 3};

  8. Declaring 2D Arrays • Same as a 1D array but a comma (,) appears in the [] characters to mark 2 dimensions • Declare a two-dimensional array with no initial elements (unitialized) private int[,] A2DList[,]; • Declare an initialized two-dimensional array with 3 elements in each dimension private int[,] A2DList = new int[3,3];

  9. Initializing 2D Arrays • Use nested initializers • Row is the innermost • Column is outermost • http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx Row 1 Row 2 Row 3 Col 2

  10. Declaring 3D Arrays • Declare a three-dimensional array with 8 (2*2*2) elements private int[,,] A3DList = new int[1,1,1];

  11. Determining Array Bounds • GetUpperBound and GetLowerBound get the largest and smallest subscript of an array dimension • An array’s lower bound is always 0 • The functions accept one argument, the 0-based dimension from which you want to get the upper or lower bound

  12. Determining Array Bounds (Example) • Get the lower and upper bound of a one-dimensional array int[] Demo = new int[] {1, 2, 3, 4, 5, 6} System.Console.WriteLine( Demo.GetLowerBound(0)) System.Console.WriteLine( Demo.GetUpperBound(0))

  13. Subscripts • You store and retrieve elements to and from an array via a subscript • The subscript value must be within the array bounds or an exception will be thrown • The number of subscripts used to reference a cell is the same as the arrays rank • One subscript for 1 dimension • Two subscripts for 2 dimensions

  14. Referencing Array Members • Declare a 1-dimensional array and store a value in the 0th element private int[] i = new int[] { 1, 2, 3 }; i[0] = 3 ; • Declare a 2-dimensional array and store a value in the centerelement (row 1, column 1) TTTState[,] A2DArray = new TTTState[3,3]; A2DArray[1,1] = TTTState.X;

  15. Examining an Array • We typically work with arrays using a loop (For loop) • Example intCurrentIndex; for (CurrentIndex = 0, DemoArray1.GetUpperBound(0), CurrentIndex++) { txtDemoArray1.AppendText(DemoArray1[CurrentIndex].ToString()); } Refer to frmMain.csPrintArray1

  16. Arrays (Characteristics 2) • Arrays work like collections in that they can be enumerated using a foreach loop • If the array has multiple dimensions, each element will be examined in row-wise order foreach(int Current in DemoArray1) { txtDemoArray1.AppendText( _ Current.ToString() + “\n”) } Next Refer to frmMain.csPrintArray1 and btnInitializeArray

  17. Arrays (Informational Members) • GetLength returns the number of elements in a particular dimension • Length gets the number of elements in all dimensions • GetUpperBound gets the largest subscript in a dimension • GetLowerBound get the smallest subscript in a dimension • Note that support has been added for arrays with Long subscripts

  18. Copying Array Elements (1) • Arrays are reference types so assignment statements assign array references rather than copying elements • Use the CopyTo method to copy the element data

  19. Copying Array Elements (2) • Call the CopyTo method on the source array as in MyArray.CopyTo • The first argument contains the destination array • The second argument contains the starting index in the destination array where elements will be copied • The destination array must have enough room to copy store the copied elements

  20. Array.CopyTo (Example) • Copy DemoArray1 to DemoArray2 (We assume 1-dimensional arrays) • Note the array is initialized using dynamic value rather than a constant integer DemoArray2 = new double[DemoArray1.GetUpperBound(0)]; DemoArray1.CopyTo(DemoArray2, 0)

  21. Arrays (Sorting) • The Sort method sorts all or part of an array in ascending order • Pass the array as the first argument • The second argument contains the starting index • The third argument contains the number of elements • The Reverse method reverses the order of the array’s elements

  22. Arrays (Sorting – Example) • Sort arrays named DemoArray1 and DemoArray2 System.Array.Sort(DemoArray1) System.Array.Sort(DemoArray2)

  23. Arrays (Reinitializing) • The Clear method reinitializes array elements • The first argument contains the array to clear • The second argument contains the starting subscript • The third argument contains the number of elements • Note the array’s size is not changed

  24. Arrays (Reinitializing – Example) • Clear (reinitialize) the array named DemoArray1 System.Array.Clear( _ DemoArray1, 0, DemoArray1.Length())

  25. Arrays (Finding Elements) • The IndexOf method searches an array for a particular value • The first argument contains the array to search • The second argument contains the search value • The optional third argument contains the index of the element where the search will begin • The method returns the index if the element is found or -1 if the element is not found Refer to frmMain.csbtnFind_Click

  26. Arrays (Finding Elements) Refer to frmMain.vbbtnFind_Click double Value; int Index; Value = ToDouble(txtValue.Text); Index = System.Array.IndexOf(DemoArray1, Value); if (Index == -1) { txtDemoArray1.AppendText("Value not found"); } else { txtDemoArray1.AppendText("Value found at index “ + Index.ToString()); }

  27. Collections (Introduction) • All lists are considered collections • Each collection references multiple objects (typically of the same type) • Collections are reference types • Each collection shares common members used to work with the collection • Indexer, add, …

  28. Collections (Important Note) • Collections are categorized into two types • Older collections (System.Collections) store references having a data type of System.Object • Generic collections are strongly typed (System.Collections.Generic) • We will talk about each in turn

  29. Collection Namespaces

  30. Collections (Enumeration) • In this context, we mean examining the items in a list (NOT REFERRING TO enum) • Enumeration is provided by implementing the IEnumerable and IEnumerator interfaces • MSDN Interface link • http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx

  31. Collections (Enumeration) • IEnumeratorprovides forward-only navigation, and interfaces • IEnumerableprovides the enumerator itself • Their members are not explicitly called • They are called by the for each loop itself

  32. Collections and Lists • IEnumerableprovides the functionality to enumerate a list • ICollection adds functionality (Add, Count Remove,Contains) • IList provides access by index or key

  33. Collections and Lists

  34. Collection / Array Relationship • The C# array declaration syntax is special • Array class implements IList but hides the add and remove members

  35. Working with Collections • Common members • Countproperty returns the number of elements in the collection • Count property is 1-based • Clearmethod removes all of the elements from the collection • ToArraymethod converts the elements in a collection into an array • ToStringmethod returns a String representing the collection’s objects

  36. Collections (The Short List) • The ArrayList maintains a list and is similar to an array • The SortedList class is very flexible and keeps items sorted • Use the Dictionary class to keep track of key/value pairs • There are others SortedDictionary, LinkedList, HashSet

  37. The ArrayList Class (Introduction) • It’s possible to manage the list by adding, updating, and removing elements • It’s possible to find elements in the list • The size of an ArrayList grows dynamically • There is no need to redimension the list

  38. The ArrayList Class (Members) • Call Add to add an item to the end of the list and Insert to add an item at a specific position • Call Remove or RemoveAt to remove an item • Call Clear to remove all items • Count and Capacity return the number of items and the number of possible (allocated) items

  39. The ArrayList Class (Adding Items) • The Add method accepts one argument – the object to add • The item is added to the end of the list • The Insert method accepts two arguments • The first contains the positional index • The second contains the object to add

  40. The ArrayList Class (Add Example) • Add a Student to the ArrayList Student s; S.RNumber = System.Convert.ToInt32(txtRNumber.Text); S.LastName = txtLastName.Text; S.FirstName = txtFirstName.Text; S.GPA = System.Convert.ToDouble(txtGPA.Text); StudentArrayList.Add(S);

  41. The ArrayList Class (Insert Example) • Insert an item at a particular position int Pos = n; Student S; S.RNumber = System.Convert.ToInt32(txtRNumber.Text); S.LastName = txtLastName.Text; S.FirstName = txtFirstName.Text; S.GPA = System.Convert.ToDouble(txtGPA.Text); StudentArrayList.Insert(Pos, S);

  42. The ArrayList Class (Removing an Item) • Call RemoveAt with the index of the item to remove • Example StudentArrayList.RemoveAt(CurrentIndex);

  43. The ArrayList Class (Enumerating) • Use a foreach loop to enumerate each element in an ArrayList • A for loop can be used but is more cumbersome foreach(object CurrentStudent In StudentArrayList) { Console.WriteLine( ((Student) CurrentStudent).RNumber.ToString()); // Other Fields }

  44. The SortedList Class (Introduction) • The SortedList operates similar to an ArrayList but the elements remain sorted • Internally, two parallel arrays are maintained • One for the keys • A second for the corresponding values • The SortedList class can become very slow so beware • Each addition or deletion requires that the indexes be updated.

  45. Adding Items to a SortedList • The Add method adds an item to a SortedList • The first argument contains the key • An exception will be thrown if the key value is a duplicate • The second argument contains the data • It can be any object • Example assuming that “S” has a data type of Student CurrentSortedList.Add(“1234”,S);

  46. Getting an Item from a SortedList • It works like an array • The key is passed as an argument to the list as follows: • Example: Student S; S.LastName = txtSLLastName.Text; S.FirstName = txtSLFirstName.Text; S.GPA = System.Convert.ToDouble(txtSLGPA.Text); StudentSortedList.[txtRNumber.Text] = S

  47. Removing an Item from a SortedList • The Remove method accepts one argument, a reference to the key to remove • The method removes the item based on the key rather than the ordinal index value • The method returns True or False depending on whether the item was removed • Example • CurrentList.Remove(“Joe”);

  48. Enumerating a SortedList • The enumerator (foreach loop) returns an element of type Dictionary • A dictionary has a key and a value • The values are returned in sorted order by key

  49. Enumerating a SortedList (Example) • Enumerate the sorted list named StudentSortedList Student CurrentStudent; Foreach (System.Collections.Dictionary de in StudentSortedList) { CurrentStudent = (Student) de.Value; // Statements to process the current // student }

  50. Other SortedList Methods • GetByIndex – Gets the record at the ordinal index value • IndexOfKey – Gets the index of a record based on a particular key

More Related