You can create two types of multidimensional arrays, as well as your own collection types while utilizing collection-utility classes.. Overview An array is a set of data items, accesse
Trang 1Hoang Anh Viet
VietHA@it-hut.edu.vn
HaNoi University of Technology
Chapter 6 Arrays, Collection
Types, and Iterators
1
Trang 2Objectives
“This chapter covers the various array and collection types available in C# You can create two types of multidimensional arrays, as well as your own collection types while utilizing collection-utility classes You’ll see how to define forward, reverse, and bidirectional iterators using the new iterator syntax introduced in C# 2.0, so that your collection types will work well with foreach statements.”
22
Trang 3Roadmap
6.1 Introduction to Arrays
6.2 Multidimentional Rectangular Arrays
6.3 Multidimentional Jagged Arrays
6.4 Collection Types
6.5 Iterators
6.6 Collection Initializers
3
Trang 46.1 Introduction to Arrays
Implicitly Typed Arrays
Type Convertibility and Covariance
The System.Array Base Class
4
Trang 5Overview
An array is a set of data items, accessed using an numerical index
An array is a group of contiguous memory locations that all have the same name and type
Arrays are reference types, and
the memory for the array is
allocated on the managed heap
Array Initialization Syntax:
Example:
100200300
myInts[0]
myInts[1]
myInts[2]
Position number of the element
within array myInts
static void SimpleArrays() {
Console.WriteLine( "=> Simple Array Creation."); // Create and fill an array of 3 Integers
int[] myInts = new int[3];
Console.WriteLine();
}
5
Trang 6Figure 6-1: Array of reference types versus value types
6
Trang 7Implicitly Typed Arrays
abbreviated way of initializing
arrays when the type of the
array can be inferred at
runtime
presented with multiple types
within the initialization list of an
implicitly typed array, it
determines a type that all the
given types are implicitly
// An implicitly typed array var implicitlyTypedArray = new [] { 4, 5, 6 };
Console.WriteLine( implicitlyTypedArray.GetType() ); // An array of doubles
var someNumbers = new [] { 3.1415, 1, 6 };
Console.WriteLine( someNumbers.GetType() ); // Won’t compile!
// var someStrings = new [] { "int", // someNumbers.GetType() };
} }
7
Trang 8Type Convertibility and Covariance
contain instances of a certain
type, the instances that may
place in that array can actually
be instances of a more derived
type
using System;
public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }
public class EntryPoint {
static void Main() {
Dog[] dogs = new Dog[3];
Cat[] cats = new Cat[2];
Animal[] animals = dogs;
Animal[] moreAnimals = cats;
} }
Dog and Cat are type-convertible
to Animal
8
Trang 9Arrays As Parameters (and Return
Values)
array, you are free to pass it as
a parameter and receive it as a
member return value
static void PrintArray(int[] myInts) {
for(int i = 0; i < myInts.Length; i++) Console.WriteLine("Item {0} is {1}", i, myInts[i]);
} static string[] GetStringArray() {
string[] theStrings = { "Hello", "from", "GetStringArray" }; return theStrings;
Pass array as parameter
Get array as return value.
9
Trang 10The System.Array Base Class
properties that are essential to an array
Clear() : set a range of elements in the array to empty values.
CopyTo() : copy elements from the source array into the
destination array
Length : return the number of items
Reverse() : reverse the contents of a one-dimensional array
Sort() : sort a one-dimensional array fo intrinsic types
Example :
10
Trang 11string[] gothicBands = { "Tones on Tail", "Bauhaus", "Sisters of Mercy" };
// Print out names in declared order.
Console.WriteLine( " -> Here is the array:");
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
Trang 12Console.WriteLine( "\n");
Array.Reverse(gothicBands);
Console.WriteLine( " -> The reversed array");
// and print them.
for (int i = 0; i <= gothicBands.GetUpperBound(0); i++)
Trang 13Roadmap
6.1 Introduction to Arrays
6.2 Multidimentional Rectangular Arrays
6.3 Multidimentional Jagged Arrays
6.4 Collection Types
6.5 Iterators
6.6 Collection Initializers
13
Trang 14dimension when declaring the
type
the array type, you must
provide the size of the
Declaration
Explicit dimension size
Figured out base on initialization expression
14
Trang 15Roadmap
6.1 Introduction to Arrays
6.2 Multidimentional Rectangular Arrays
6.3 Multidimentional Jagged Arrays
6.4 Collection Types
6.5 Iterators
6.6 Collection Initializers
15
Trang 166.3 Multidimensional Jagged Arrays
A jagged array is an array of arrays
Each of the rows need not be the same size as all the others, a
graphical representation of the array would not be square.
Create a jagged array:
Declaration
Has different size
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 1, 2, 3, 4, 5 };
jagged[2] = new int[] { 6, 5, 4 };
foreach (int[] ar in jagged)
16
Trang 17StringBuilder sb = new StringBuilder();
foreach (int n in ar)
StringBuilder sb = new StringBuilder();
for (int j = 0; j < jagged[i].Length; ++j)
Trang 187 int [][] jagged = new int [3][];
8 jagged[0] = new int [] { 1, 2 };
9 jagged[1] = new int [] { 1, 2, 3, 4, 5 };
10 jagged[2] = new int [] { 6, 5, 4 };
11 foreach ( int [] ar in jagged)
12 {
13 StringBuilder sb = new StringBuilder ();
14 foreach ( int n in ar)
23 StringBuilder sb = new StringBuilder ();
24 for ( int j = 0; j < jagged[i].Length; ++j)
Trang 19Roadmap
6.1 Introduction to Arrays
6.2 Multidimentional Rectangular Arrays
6.3 Multidimentional Jagged Arrays
6.4 Collection Types
6.5 Iterators
6.6 Collection Initializers
19
Trang 206.4 Collection Types
Ever since its inception, the NET Framework has offered a host of collection types for managing everything from an expandable array via ArrayList, a Queue, a Stack, or even a dictionary via the HashTable class Over the years, newer version of the NET Framework expanded these types Generally, a collection is any type that holds on to a set of objects and implements IEnumerable
or IEnumerable<T> The objects in the set are typically related to each other in some way defined by the problem domain.
20
Trang 216.4 Collection Types(2)
The Interface of the System.Collections
Namespace
The Class Types of System.Collections
The Sytem.Collections.Generic Namespace
21
Trang 22The Interface of the System.Collections Namespace
Amajority of the classes within System.Collections implement these interfaces to provide access to their contents
Allows Containers to automatically resize themselves
22
Trang 24The Role of ICollection
The number of items in the container
The thread safety of the container
The ability to copy the contents into a System.Array type
void CopyTo(Array array, int index);
}
24
Trang 25The Role of IDictionary
Contains() methods.
public interface IDictionary : ICollection, IEnumerable {
bool IsFixedSize { get; } bool IsReadOnly { get; } // Type indexer
object this[object key] { get; set; } ICollection Keys { get; }
ICollection Values { get; } void Add(object key, object value);
Trang 26The Role of IList
a container
bool IsFixedSize { get; } bool IsReadOnly { get; } object this[ int index ] { get; set; } int Add(object value);
void Clear();
bool Contains(object value);
int IndexOf(object value);
void Insert(int index, object value);
void Remove(object value);
void RemoveAt(int index);
}
26
Trang 28// Public fields for simplicity.
public string PetName;
public int Speed;
Trang 29static void ArrayListTest()
{
Console.WriteLine( "\n=> ArrayList Test:\n");
ArrayList carArList = new ArrayList();
carArList.AddRange(new Car[] { new Car( "Fred", 90, 10),
new Car( "Mary", 100, 50), new Car( "MB", 190, 11)});
Console.WriteLine( "Items in carArList: {0}", carArList.Count);
// Print out current values.
foreach(Car c in carArList)
Console.WriteLine( "Car pet name: {0}", c.PetName);
Console.WriteLine( "->Inserting new Car.");
carArList.Insert(2, new Car( "TheNewCar", 0, 12));
Console.WriteLine("Items in carArList: {0}", carArList.Count);
object[] arrayOfCars = carArList.ToArray();
for(int i = 0; i < arrayOfCars.Length; i++)
Print out # of items in ArrayList.
Insert a new item.
Get object array from ArrayList
Trang 30Working with the Queue Type
Queues are containers that ensure items are accessed using a
first-in, first-out manner
Queue
removing it
30
Trang 31The System.Collections.Generic
Namespace
Contains numerous class and interface types that allow you to
contain subitems in a variety of containers
Similar to System.Collections but more general
Differences:
• TValue : used for values
31
Trang 33Roadmap
6.1 Introduction to Arrays
6.2 Multidimentional Rectangular Arrays
6.3 Multidimentional Jagged Arrays
6.4 Collection Types
6.5 Iterators
6.6 Collection Initializers
33
Trang 346.5 Iterators
When the enumerable object calls GetEnumerator , either directly or indirectly, the compiler generates and returns an appropriate iterator object
34
Trang 35Enumerable Objects
public interface IEnumerable<T> : IEnumerable {
to enumerate nongeneric
collections
35
Trang 36Enumerators
Enumerators are part of the enumeration pattern and normally
implemented as a nested class within the collection type
public interface IEnumerator<T> : IEnumerator, IDisposable {
T Current { get; } }
public interface IEnumerator {
object Current { get; } bool MoveNext();
Returns the enumeration
to the beginning of the
collection
36
Trang 37 The enumerator is the state machine representing the enumeration
Part of the state machine is the cursor, which is the collection index
or locator
When the enumerator is created, the cursor initially points before the first element of the collection
the Current property to the next element of the collection
The Reset method resets the enumeration He cursor is updated to point to before the collection again
37
Trang 38elements = new object[items.Length];
Array.Copy(items, elements, items.Length);
Trang 39throw new InvalidOperationException(
"Enumeration already finished");
}
if (cursor == -1)
{
throw new InvalidOperationException(
"Enumeration not started");
}
return elements[cursor];
}
}
private int cursor;
private object[] elements = null;
}
private object[] items = null;
}
}
Trang 41IEnumerable<T>, IEnumerator<T>,
IEnumerable, and IEnumerator
The C# foreach statement iterates over a collection of objects,
including a System.Array, ArrayList, List<T>…which implement the IEnumerable<T> or IEnumerable interface
These interfaces allow iterating easier and more friendly
Definitions:
41
Trang 43The statement expression is assigned to the Current property
43
Trang 44Iterator block
Contains the logic to enumerate a
collection
Includes one or more yield statements
Methods,properties, and operator function can be iterator block
Maintains the state machine of the
enumerator between iterations
44
Trang 45{ Console.WriteLine(n);
} } }
Trang 46Roadmap
6.1 Introduction to Arrays
6.2 Multidimentional Rectangular Arrays
6.3 Multidimentional Jagged Arrays
6.4 Collection Types
6.5 Iterators
6.6 Collection Initializers
46
Trang 476.6 Collection Initializers
C# 3.0 introduces a new abbreviated syntax for initializing
collections
For each item in the collection initialization list, the compiler
generates a call to the collection’s Add() method
The collection type must implement ICollection<T>
Each item in the collection initialization list must be implicitly
convertible to the type T
47
Trang 48var developmentTeam = new List<Employee> {
new Employee { Name = "Michael Bolton" },
new Employee { Name = "Samir Nagheenanajar" },
new Employee { Name = "Peter Gibbons" }
};
Console.WriteLine( "Development Team:" );
Trang 49Summary
I’ve introduced you about arrays and collections which are very
useful to store values and imply the relations between stored types
I ‘ve also supplied the use of arraylist and queue and how to
enumerate items with foreach statement
49