Chapter06 Array, Collection Types, And Iterators
-
Upload
nguyen-ngoc-lieu -
Category
Documents
-
view
242 -
download
0
Transcript of Chapter06 Array, Collection Types, And Iterators
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
1/49
Hoang Anh [email protected]
HaNoi University of Technology
Chapter 6. Arrays, Collection
Types, and Iterators
1
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
2/49
Microsoft
Objectives
This chapter covers the various array and collection typesavailable in C#. You can create two types ofmultidimensional arrays, as well as your own collection
types while utilizing collection-utility classes. Youll seehow to define forward, reverse, and bidirectional iteratorsusing the new iterator syntax introduced in C# 2.0, sothat your collection types will work well with foreachstatements.
2
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
3/49
Microsoft
Roadmap
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
4/49
Microsoft
6.1. Introduction to Arrays
Overview
Implicitly Typed Arrays
Type Convertibility and Covariance
Arrays As Parameters (and Return Values)
The System.Array Base Class
4
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
5/49
Microsoft
Overview
An array is a set of data items, accessed using an numerical index
An array is a group of contiguous memory locations that all havethe same name and type
Arrays are reference types, and
the memory for the array is
allocated on the managed heap.
Array Initialization Syntax:
Example:
100
200
300
myInts[0]
myInts[1]
myInts[2]
Position number of the elementwithin array myInts
static void SimpleArrays(){
Console.WriteLine("=> Simple Array Creation.");
// Create and fill an array of 3 Integers
int[] myInts = new int[3];
myInts[0] = 100;
myInts[1] = 200;
myInts[2] = 300;
// Now print each value.foreach(int i in myInts)
Console.WriteLine(i);
Console.WriteLine();
}
5
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
6/49
Microsoft
Figure 6-1: Array of reference types versus value types
6
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
7/49
Microsoft
Implicitly Typed Arrays
C# 3.0 introduces anabbreviated way of initializingarrays when the type of thearray can be inferred at
runtime When the compiler is
presented with multiple typeswithin the initialization list of animplicitly typed array, it
determines a type that all thegiven types are implicitlyconvertible to.
Example:
using System;
public class EntryPoint
{
static void Main()
{
// A conventional array
int[] conventionalArray = new int[] { 1, 2, 3 };// 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() );
// Wont compile!// var someStrings = new [] { "int",
// someNumbers.GetType() };
}
}
7
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
8/49
Microsoft
Type Convertibility and Covariance
When declaring an array to
contain instances of a certain
type, the instances that may
place in that array can actuallybe instances of a more derived
type.
Arrays are covariant
Example:
using System;
public classAnimal { }
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 toAnimal
8
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
9/49
Microsoft
Arrays As Parameters (and Return
Values) Once you have created an
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;
}
static void PassAndReceiveArrays()
{
Console.WriteLine("=>Arrays as params and return values.");
. int[] ages = {20, 22, 23, 0} ;
PrintArray(ages);
string[] strs = GetStringArray();
foreach(string s in strs)
Console.WriteLine(s);
Console.WriteLine();
}
Pass array as parameter
Get array as return value.
9
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
10/49
Microsoft
The System.Array Base Class
The System.Array type houses the fundamental methodsand properties that are essential to an array
Some members: 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
Rank: return the number of dimensions
Reverse() : reverse the contents of a one-dimensional array
Sort() : sort a one-dimensional array fo intrinsic types
Example:
10
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
11/49
using System;
namespace ConsoleApplication11
{
class Program
{static void Main()
{
SystemArrayFunctionality();
Console.ReadLine();
}
static void SystemArrayFunctionality()
{
Console.WriteLine("=> Working with System.Array.");
.
string[] 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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
12/49
Console.WriteLine("\n");
Array.Reverse(gothicBands);
Console.WriteLine(" -> The reversed array");
// ... and print them.
for (int i = 0; i
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
13/49
Microsoft
Roadmap
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
14/49
Microsoft
6.2. Multidimensional Rectangular
Arrays Each row contains the same
number of columns
Dont need the size of each
dimension when declaring thetype
When creating an instance of
the array type, you must
provide the size of the
dimensions. Get the count of each
dimension: Array.GetLength
using System;public class EntryPoint
{
static void Main()
{
int[,] twoDim1 = new int[5, 3];
int[,] twoDim2 = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
foreach (int i in twoDim2)
{
Console.WriteLine(i);}
}
}
Declaration
Explicit
dimension
size
Figured out
base on
initialization
expression
14
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
15/49
Microsoft
Roadmap
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
16/49
Microsoft
6.3 Multidimensional Jagged Arrays
A jagged arrayis 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:
Declare the number of rows in array.
Each row will hold an array, which can be of any length.
These arrays must each be declared.
Then fill in the values for the elements in these "inner" arrays.
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
17/49
Microsoft
Use fo r
statement
foreach (int[] ar in jagged)
{
StringBuilder sb = new StringBuilder();
foreach (int n in ar){
sb.AppendFormat("{0}", n);
}
Console.WriteLine(sb.ToString());
}
for (int i = 0; i < jagged.Length; ++i)
{
StringBuilder sb = new StringBuilder();
for (int j = 0; j < jagged[i].Length; ++j)
{
sb.AppendFormat("{0} ", jagged[i][j]);
}
Console.WriteLine(sb.ToString());
}
Use foreach
statement
17
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
18/49
Microsoft
1. using System;
2. using System.Text;
3. publicclassEntryPoint
4. {
5. staticvoidMain()
6. {7. int[][] jagged = newint[3][];
8. jagged[0] = newint[] { 1, 2 };
9. jagged[1] = newint[] { 1, 2, 3, 4, 5 };
10. jagged[2] = newint[] { 6, 5, 4 };
11. foreach (int[] ar in jagged)
12. {
13. StringBuilder sb = newStringBuilder();
14. foreach (int n in ar)
15. {
16. sb.AppendFormat("{0} ", n);
17. }
18. Console.WriteLine(sb.ToString());
19. }
20. Console.WriteLine();
21. for (int i = 0; i < jagged.Length; ++i)
22. {
23. StringBuilder sb = newStringBuilder();
24. for (int j = 0; j < jagged[i].Length; ++j)
25. {
26. sb.AppendFormat("{0} ", jagged[i][j]);
27. }
28. Console.WriteLine(sb.ToString());
29. }
30. }
31. }
18
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
19/49
Microsoft
Roadmap
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
20/49
Microsoft
6.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 HashTableclass. 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. Theobjects in the set are typically related to each other in
some way defined by the problem domain.
20
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
21/49
Microsoft
6.4. Collection Types(2)
The Interface of the System.Collections
Namespace
The Class Types of System.Collections
The Sytem.Collections.Generic Namespace
21
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
22/49
Microsoft
The Interface of the System.Collections
Namespace
The System.Collections namespace defines a number of
interfaces
Amajority of the classes within System.Collections
implement these interfaces to provide access to their
contents
Allows Containers to automatically resize themselves
22
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
23/49
Microsoft
The Interface of the System.Collections
Namespace(2) Interface ofSystem.Collections
ICollect ion
Defines general characteristics for all nongeneric collection types IComparer
Allows two objects to be compared
IDict ionary Allows a nongeneric collection object to represent its contents using
name/value pairs IDict ionaryEnumerator
IEnumerable
Return the IEnumerator interface for a given object. IEnumerator
Enables foreach style iteration fo subtypes IHashCodeProvider
IL ist
Provides behavior to add,remove, and index items in a list of objects
23
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
24/49
Microsoft
The Role of ICollection
Provides a small set of members that allow to determine
The number of items in the container
The thread safety of the container
The ability to copy the contents into a System.Array type Definition:
public interface ICollection : IEnumerable
{
int Count { get; }
bool IsSynchronized { get; }object SyncRoot { get; }
void CopyTo(Array array, int index);
}
24
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
25/49
Microsoft
The Role of IDictionary
A dictionary is a collection that maintains a set of name/value pairs
Defines a Keys and Values property andAdd(), Remove(),
Contains() methods.
Definition:
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);
void Clear();
bool Contains(object key);
IDictionaryEnumerator GetEnumerator();
void Remove(object key);
} 25
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
26/49
Microsoft
The Role of IList
Provides the ability to insert, remove, and index items into (or out of)
a container
Definitionpublic interface IList :ICollection, IEnumerable
{
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
27/49
Microsoft
The Class Types of System.Collections
ArrayList
Represents a dynamically sizd array of objects
Hashtable
Represents a collection of objects identified by a numerical Queue
Represents a standard FIFO queue
SortedList
Like a dictionary
The elements can be accessed by ordinal position
Stack
A FIFO queue providing push and pop( and peek) functionality
27
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
28/49
Microsoft
Working with ArrayList Type
Example:
Our ArrayList maintains a set of Car objects
ArrayListTest()
Constructors
Field
class Car
{
// Public fields for simplicity.
public string PetName;
public int Speed;
// Constructors.
public Car(){}public Car(string name, int currentSpeed)
{ PetName = name; Speed = currentSpeed;}
}
28
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
29/49
static 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++)
{
Console.WriteLine("Car pet name: {0}",
((Car)arrayOfCars[i]).PetName);
}
}
Create
ArrayList
Print out # of
items in
ArrayList.
Insert a new
item.
Get object array
from ArrayList
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
30/49
Microsoft
Working with the Queue Type
Queues are containers that ensure items are accessed
using a first-in, first-out manner
Members of the Queue Type:
Dequeue(): Removes and returns the object at the beginning ofthe Queue
Enqueue(): Adds an object to the end of the Queue
Peek(): Returns the object at the beginning of the Queue withoutremoving it
30
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
31/49
Microsoft
The 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:
T
keyword: used to represent types TKeykeyword: used for keys
TValue: used for values
31
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
32/49
Microsoft
Interfaces:
ICollection
IComparer
IDictionary
IEnumerable
IEnumerator
IList
32
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
33/49
Microsoft
Roadmap
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
34/49
Microsoft
6.5. Iterators
Implement the enumerator pattern
When the enumerable object calls GetEnumerator, either
directly or indirectly, the compiler generates and returns
an appropriate iterator object.
Can be a combined enumerable and enumerator object
Do not implement the Resetmethod
34
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
35/49
Microsoft
Enumerable Objects
Enumerable objects implement the IEnumerable
interface
public interface IEnumerable : IEnumerable{
IEnumerator GetEnumerator();
}
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
Returns an
enumerator,which is used
to enumerate nongeneric
collections
35
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
36/49
Microsoft
Enumerators
Enumerators are part of the enumeration pattern and
normally implemented as a nested class within the
collection type
Enumerators implement the IEnumerator interface
public interface IEnumerator : IEnumerator, IDisposable
{
T Current { get; }
}
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
Returns the current
element of the collection
Moves the Current
property to the next
element
Returns the enumeration to
the beginning of the
collection
36
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
37/49
Microsoft
The enumerator is the state machine representing the enumeration
Part of the state machine is the cursor, which is the collection indexor locator
When the enumerator is created, the cursor initially points before thefirst element of the collection
The MoveNext method increments the value of the cursur to movethe Current property to the next element of the collection
The Reset method resets the enumeration. He cursor is updated topoint to before the collection again
37
E l
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
38/49
Example
38
public class SimpleCollection : IEnumerable
{
public SimpleCollection(object[] array)
{
items = array;
}
public IEnumerator GetEnumerator(){
return new Enumerator(items);
}
private class Enumerator : IEnumerator
{
public Enumerator(object[] items)
{
elements = new object[items.Length];
Array.Copy(items, elements, items.Length);cursor = -1;
}
public bool MoveNext()
{
++cursor;
if (cursor > (elements.Length - 1))
{
return false;
}
return true;
}
public void Reset()
{
cursor = -1;
}
Example
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
39/49
Example
39
public object Current
{
get
{
if (cursor > (elements.Length - 1))
{throw 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;}
}
Example
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
40/49
Example
40
using System;
using System.Collections;
namespace Donis.CSharpBook
{
public class Starter{
public static void Main()
{
SimpleCollection simple = new SimpleCollection(
new object[] { 1, 2, 3, 4, 5, 6, 7 });
IEnumerator enumerator = simple.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
}
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
41/49
Microsoft
IEnumerable, IEnumerator,
IEnumerable, and IEnumerator
The C# foreach statement iterates over a collection of
objects, including a System.Array, ArrayList,
Listwhich implement the IEnumerable or
IEnumerable interface
These interfaces allow iterating easier and more friendly
Definitions:
41
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
42/49
Microsoft
public interface IEnumerable : IEnumerable
{ IEnumerator GetEnumerator();
}
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
public interface IEnumerator : IEnumerator, IDisposable
{
T Current { get; }
}
public interface IEnumerator
{ object Current { get; }
bool MoveNext();
void Reset();
}
42
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
43/49
Microsoft
Yield Statement
Syntax:
yield return expression;
yield break;
The yield return statements iterate the next element of acollection. The statement expression is assigned to the
Current property
The yield breakstatements finish an enumeration
43
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
44/49
Microsoft
Iterator 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 theenumerator between iterations
44
Example
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
45/49
Example
45
using System;
using System.Collections;
using System.Collections.Generic;
public class MyColl : IEnumerable
{
public MyColl(T[] items)
{
this.items = items;
}
public IEnumerator GetEnumerator()
{
foreach (T item in items){
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private T[] items;
}
public class EntryPoint
{
static void Main(){
MyColl integers =
new MyColl(new int[] { 1, 2, 3, 4 });
foreach (int n in integers)
{
Console.WriteLine(n);
}
}}
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
46/49
Microsoft
Roadmap
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
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
47/49
Microsoft
6.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 collections Add()method
The collection type must implement ICollection
Each item in the collection initialization list must be
implicitly convertible to the type T
47
Example
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
48/49
Example
48
using System;
using System.Collections.Generic;
public class Employee
{
public string Name { get; set; }
}public class CollInitializerExample
{
static void Main()
{
var developmentTeam = new List {
new Employee { Name = "Michael Bolton" },
new Employee { Name = "Samir Nagheenanajar" },
new Employee { Name = "Peter Gibbons" }
};
Console.WriteLine( "Development Team:" );
foreach( var employee in developmentTeam )
{
Console.WriteLine( "\t" + employee.Name );}
}
}
New way to
initialzing
collection
-
7/27/2019 Chapter06 Array, Collection Types, And Iterators
49/49
Summary
Ive 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 andhow to enumerate items with foreach statement