Working With C# Arrays And .NET Lists

67
Working With C# Arrays And .NET Lists

description

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 - PowerPoint PPT Presentation

Transcript of Working With C# Arrays And .NET Lists

Page 1: Working With C# Arrays And .NET Lists

Working With C# Arrays And .NET Lists

Page 2: Working With C# Arrays And .NET Lists

Slide 2

Lecture Overview Discuss arrays Discuss the various types of lists

available through C# and the .NET Framework

Page 3: Working With C# Arrays And .NET Lists

Slide 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

Page 4: Working With C# Arrays And .NET Lists

Slide 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.}

Page 5: Working With C# Arrays And .NET Lists

Slide 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.CopyTo

Refer to frmMain.btnCopyArray_Click

Page 6: Working With C# Arrays And .NET Lists

Slide 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;

Page 7: Working With C# Arrays And .NET Lists

Slide 7

Declaring 1D Arrays Declare a one-dimensional array with no

initial elementsprivate 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 itprivate int[] Alist = new int[]

{1, 2, 3};

Page 8: Working With C# Arrays And .NET Lists

Slide 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 dimensionprivate int[,] A2DList = new int[3,3];

Page 9: Working With C# Arrays And .NET Lists

Slide 9

Initializing 2D Arrays Use nested initializers

Row is the innermost Column is outermost http://

msdn.microsoft.com/en-us/library/2yd9wwz4.aspx

Row 1Row 2Row 3

Col 2

Page 10: Working With C# Arrays And .NET Lists

Slide 10

Declaring 3D Arrays Declare a three-dimensional array with

8 (2*2*2) elements private int[,,] A3DList = new int[1,1,1];

Page 11: Working With C# Arrays And .NET Lists

Slide 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

Page 12: Working With C# Arrays And .NET Lists

Slide 12

Determining Array Bounds (Example) Get the lower and upper bound of a

one-dimensional arrayint[] Demo = new int[] {1, 2, 3, 4, 5, 6}System.Console.WriteLine( Demo.GetLowerBound(0))System.Console.WriteLine( Demo.GetUpperBound(0))

Page 13: Working With C# Arrays And .NET Lists

Slide 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

Page 14: Working With C# Arrays And .NET Lists

Slide 14

Referencing Array Members Declare a 1-dimensional array and store

a value in the 0th elementprivate int[] i = new int[] { 1, 2, 3 };i[0] = 3 ;

Declare a 2-dimensional array and store a value in the center element (row 1, column 1)TTTState[,] A2DArray = new TTTState[3,3];

A2DArray[1,1] = TTTState.X;

Page 15: Working With C# Arrays And .NET Lists

Slide 15

Examining an Array We typically work with arrays using a

loop (For loop) Example

int CurrentIndex;for (CurrentIndex = 0, DemoArray1.GetUpperBound(0),

CurrentIndex++){ txtDemoArray1.AppendText(DemoArray1[CurrentInde

x].ToString());}

Refer to frmMain.cs PrintArray1

Page 16: Working With C# Arrays And .NET Lists

Slide 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.cs PrintArray1 and btnInitializeArray

Page 17: Working With C# Arrays And .NET Lists

Slide 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

Page 18: Working With C# Arrays And .NET Lists

Slide 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

Page 19: Working With C# Arrays And .NET Lists

Slide 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

Page 20: Working With C# Arrays And .NET Lists

Slide 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)

Page 21: Working With C# Arrays And .NET Lists

Slide 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

Page 22: Working With C# Arrays And .NET Lists

Slide 22

Arrays (Sorting – Example) Sort arrays named DemoArray1 and

DemoArray2

System.Array.Sort(DemoArray1)

System.Array.Sort(DemoArray2)

Page 23: Working With C# Arrays And .NET Lists

Slide 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

Page 24: Working With C# Arrays And .NET Lists

Slide 24

Arrays (Reinitializing – Example) Clear (reinitialize) the array named

DemoArray1

System.Array.Clear( _ DemoArray1, 0, DemoArray1.Length())

Page 25: Working With C# Arrays And .NET Lists

Slide 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 foundRefer to frmMain.cs

btnFind_Click

Page 26: Working With C# Arrays And .NET Lists

Slide 26

Arrays (Finding Elements)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());}

Refer to frmMain.vb btnFind_Click

Page 27: Working With C# Arrays And .NET Lists

Slide 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, …

Page 28: Working With C# Arrays And .NET Lists

Slide 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

Page 29: Working With C# Arrays And .NET Lists

Slide 29

Collection Namespaces

Page 30: Working With C# Arrays And .NET Lists

Slide 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

Page 31: Working With C# Arrays And .NET Lists

Slide 31

Collections (Enumeration) IEnumerator provides forward-only

navigation, and interfaces IEnumerable provides the enumerator

itself Their members are not explicitly called

They are called by the for each loop itself

Page 32: Working With C# Arrays And .NET Lists

Slide 32

Collections and Lists IEnumerable provides the functionality

to enumerate a list ICollection adds functionality (Add,

Count Remove,Contains) IList provides access by index or key

Page 33: Working With C# Arrays And .NET Lists

Slide 33

Collections and Lists

Page 34: Working With C# Arrays And .NET Lists

Slide 34

Collection / Array Relationship The C# array declaration syntax is

special Array class implements IList but hides

the add and remove members

Page 35: Working With C# Arrays And .NET Lists

Slide 35

Working with Collections Common members

Count property returns the number of elements in the collection

Count property is 1-based Clear method removes all of the elements

from the collection ToArray method converts the elements in a

collection into an array ToString method returns a String

representing the collection’s objects

Page 36: Working With C# Arrays And .NET Lists

Slide 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

Page 37: Working With C# Arrays And .NET Lists

Slide 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

Page 38: Working With C# Arrays And .NET Lists

Slide 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

Page 39: Working With C# Arrays And .NET Lists

Slide 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

Page 40: Working With C# Arrays And .NET Lists

Slide 40

The ArrayList Class (Add Example) Add a Student to the ArrayListStudent 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);

Page 41: Working With C# Arrays And .NET Lists

Slide 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);

Page 42: Working With C# Arrays And .NET Lists

Slide 42

The ArrayList Class (Removing an Item) Call RemoveAt with the index of the item

to remove

Example

StudentArrayList.RemoveAt(CurrentIndex);

Page 43: Working With C# Arrays And .NET Lists

Slide 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}

Page 44: Working With C# Arrays And .NET Lists

Slide 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.

Page 45: Working With C# Arrays And .NET Lists

Slide 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);

Page 46: Working With C# Arrays And .NET Lists

Slide 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

Page 47: Working With C# Arrays And .NET Lists

Slide 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”);

Page 48: Working With C# Arrays And .NET Lists

Slide 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

Page 49: Working With C# Arrays And .NET Lists

Slide 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

}

Page 50: Working With C# Arrays And .NET Lists

Slide 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

Page 51: Working With C# Arrays And .NET Lists

Slide 51

GENERICS

Page 52: Working With C# Arrays And .NET Lists

Slide 52

Introduction to Generics For our purposes, generics store items

all having the same data type For example, there is a generic List class

that replaces the non-generic ArrayList class

Advantages They simplify coding They “almost” eliminate any type

conversion errors They are faster

Page 53: Working With C# Arrays And .NET Lists

Slide 53

Generic Collections (Declaring) The syntax is similar to declaring any

other collection or variable The data types of the key and possibly

value appear in <> after the data type declaration

The List class is the generic version of the ArrayList class

private List<Student> StudentGenericList = new List<Student>();

Page 54: Working With C# Arrays And .NET Lists

Slide 54

Generic collections (Members) The generic members are the same as

the non-generic members Differences appear when

Referencing an item Enumerating the items

Page 55: Working With C# Arrays And .NET Lists

Slide 55

List<T> (Adding) Add to the end of the list

Public void Add(T item) Add a list of items

Public void AddRange (Ienumerable<T> collection

Add item at index Public void Insert(int Index, T item)

Page 56: Working With C# Arrays And .NET Lists

Slide 56

List<T> (Removing) Remove a specific item

Public bool Remove (T item) Remove at ordinal position

Public void RemoveAt(int index) Remove n consecutive items

Public void RemoveRange(int index, int count)

Page 57: Working With C# Arrays And .NET Lists

Slide 57

Referencing a Generic Item No explicit type conversion is necessary

because a generic can only store references to one type

Example (assume that argIndex is the ordinal index of the desired item:

Student s;s = StudentGenericList[argIndex];

Page 58: Working With C# Arrays And .NET Lists

Slide 58

Dictionaries (Introduction) Dictionaries are just key / value pairs Taxonomy

Sorted or unsorted Access by key and/or position Generic and non-generic versions

Performance characteristics of large dictionaries

Page 59: Working With C# Arrays And .NET Lists

Slide 59

Generic Sorted Dictionaries SortedDictionary performs well with

any insertion / removal scenario Items must be accessed by key

SortedList performs well when retrieving elements but poorly when inserting them Items can be accessed by index or key

These are just sorted version of the other Dictionary

Page 60: Working With C# Arrays And .NET Lists

Slide 60

Enumerating a Generic List Enumerating a generic list is simplified

too because we no longer have to cast the type

foreach( Student CurrentStudent in StudentGenericList)

Console.WriteLine(CurrentStudent.Rnumber);

next

Page 61: Working With C# Arrays And .NET Lists

Slide 61

SPECIALIZED LISTS

Page 62: Working With C# Arrays And .NET Lists

Slide 62

Queue Class A Queue stores a list of objects much

like an ArrayList stores a list of objects Queues are first-in first-out data structures The first item added to a queue is the first

item removed from the queue

Page 63: Working With C# Arrays And .NET Lists

Slide 63

Operation of a Queue

Page 64: Working With C# Arrays And .NET Lists

Slide 64

Queue Methods and Properties Dequeue method returns the element at the

front of the queue and removes that element from the queue

Enqueue method adds an element to the back of the queue

Peek method returns the element at the front of the queue but does not remove the element from the queue

Count property gets the number of elements stored in the queue

Page 65: Working With C# Arrays And .NET Lists

Slide 65

Stack Class A stack is a last-in, first-out list The item most recently added to the

stack is the first item removed from the stack

Page 66: Working With C# Arrays And .NET Lists

Slide 66

Operation of a Stack

Page 67: Working With C# Arrays And .NET Lists

Slide 67

Stack Methods and Properties Push method adds an item to the stack Pop method returns the most recently

added item from stack The item returned is also removed from

the stack Peek method returns the object at the

top of the stack without removing it Count property contains the number of

elements in the stack