Professional Documents
Culture Documents
Objectives
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. Youll 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.
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
Microsoft
Overview
Implicitly Typed Arrays
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 have the same name and type Arrays are reference types, and static void SimpleArrays() the memory for the array is { Console.WriteLine("=> Simple Array Creation."); allocated on the managed heap. // Create and fill an array of 3 Integers Array Initialization Syntax: int[] myInts = new int[3];
Example:
myInts[0]
myInts[0] = 100; myInts[1] = 200; myInts[2] = 300; // Now print each value. foreach(int i in myInts) Console.WriteLine(i); Console.WriteLine();
myInts[2]
Microsoft
C# 3.0 introduces an abbreviated way of initializing arrays when the type of the array can be inferred at runtime When the compiler is presented with multiple types within the initialization list of an implicitly typed array, it determines a type that all the given types are implicitly convertible 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() }; } }
Microsoft
When declaring an array to contain instances of a certain type, the instances that may place in that array can actually be instances of a more derived type. Arrays are covariant Example:
using System; public class Animal { } public class Dog : Animal { } public class Cat : Animal { } public class EntryPoint Dog and Cat are { type-convertible to Animal static void Main() { Dog[] dogs = new Dog[3]; Cat[] cats = new Cat[2]; Animal[] animals = dogs; Animal[] moreAnimals = cats; } }
Microsoft
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(); }
Microsoft
The System.Array type houses the fundamental methods and 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
Microsoft
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 <= gothicBands.GetUpperBound(0); i++) { // Print a name Console.Write(gothicBands[i] + " "); }
Console.WriteLine("\n"); Array.Reverse(gothicBands); Console.WriteLine(" -> The reversed array"); // ... and print them. for (int i = 0; i <= gothicBands.GetUpperBound(0); i++) { // Print a name Console.Write(gothicBands[i] + " "); } Console.WriteLine("\n"); . Console.WriteLine(" -> Cleared out all but one..."); Array.Clear(gothicBands, 1, 2); for (int i = 0; i <= gothicBands.GetUpperBound(0); i++) { // Print a name Console.Write(gothicBands[i] + " "); } Console.WriteLine(); } } }
Reverse array
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
Microsoft
13
Each row contains the same number of columns Dont need the size of each dimension when declaring the type When creating an instance of the array type, you must provide the size of the dimensions. Get the count of each dimension: Array.GetLength
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
Microsoft
14
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
Microsoft
15
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
Declare the number of rows in array. Each row will hold an array, which can be of any length. int[][] jagged = new int[3][]; These arrays must each = be declared. jagged[0] new int[] { 1, 2 }; jagged[1] new int[] { 1, 2, 3, 5 }; "inner" arrays. Then fill in the values for=the elements in4, these Has different
jagged[2] = new int[] { 6, 5, 4 }; foreach (int[] ar in jagged)
size
Microsoft
16
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()); } foreach (int[] ar in jagged) { StringBuilder sb = new StringBuilder(); foreach (int n in ar) { sb.AppendFormat("{0}", n); } Console.WriteLine(sb.ToString()); } Microsoft
17
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.
using System; using System.Text; public class EntryPoint { static void Main() { 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) { StringBuilder sb = new StringBuilder(); foreach (int n in ar) { sb.AppendFormat("{0} ", n); } Console.WriteLine(sb.ToString()); } Console.WriteLine(); 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()); } } }
Microsoft
18
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
Microsoft
19
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.
Microsoft
20
Microsoft
21
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
Microsoft
22
Interface of System.Collections
ICollection
Defines general characteristics for all nongeneric collection types Allows two objects to be compared Allows a nongeneric collection object to represent its contents using name/value pairs Return the IEnumerator interface for a given object. Enables foreach style iteration fo subtypes Provides behavior to add,remove, and index items in a list of objects
IComparer IDictionary
IDictionaryEnumerator IEnumerable
Microsoft
23
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
Microsoft
A dictionary is a collection that maintains a set of name/value pairs Defines a Keys and Values property and Add(), Remove(), Contains() methods. public interface IDictionary : ICollection, IEnumerable Definition:
{
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);
Microsoft }
25
Provides the ability to insert, remove, and index items into (or out of) a container public interface IList :ICollection, IEnumerable Definition {
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); }
Microsoft
26
ArrayList
Represents a dynamically sizd array of objects Represents a collection of objects identified by a numerical Represents a standard FIFO queue
Hashtable
Queue
SortedList
Stack
Microsoft
27
Example:
Field
Constructors
Microsoft
ArrayListTest()
28
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
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 of
the Queue
Microsoft
30
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 TKey keyword: used for keys TValue: used for values
Microsoft
31
Microsoft
32
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
Microsoft
33
6.5. Iterators
Microsoft
Enumerable Objects
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<T> : IEnumerator, IDisposable { Returns the current T Current { get; } element of the collection } public interface IEnumerator { object Current { get; } bool MoveNext(); Moves the Current void Reset(); property to the next } element
36
Microsoft
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 MoveNext method increments the value of the cursur to move 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
Microsoft
37
Example
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; }
38
Example
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; } }
39
Example
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); } } }
40
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:
Microsoft
41
public interface IEnumerable<T> : IEnumerable { IEnumerator<T> GetEnumerator(); } public interface IEnumerable { IEnumerator GetEnumerator(); }
public interface IEnumerator<T> : IEnumerator, IDisposable { T Current { get; } } public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); }
Microsoft
42
Yield Statement
Syntax:
The yield return statements iterate the next element of a collection. The statement expression is assigned to the Current property The yield break statements finish an enumeration
Microsoft
43
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 the enumerator between iterations
Microsoft
44
Example
using System; using System.Collections; using System.Collections.Generic; public class MyColl<T> : IEnumerable<T> { public MyColl(T[] items) { this.items = items; } public IEnumerator<T> GetEnumerator() { foreach (T item in items) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private T[] items; }
public class EntryPoint { static void Main() { MyColl<int> integers = new MyColl<int>(new int[] { 1, 2, 3, 4 }); foreach (int n in integers) { Console.WriteLine(n); } } }
45
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
Microsoft
46
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<T> Each item in the collection initialization list must be implicitly convertible to the type T
Microsoft
47
using System; using System.Collections.Generic; public class Employee { public string Name { get; set; } } public class CollInitializerExample { static void Main() { var developmentTeam = new List<Employee> { 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 ); } } }
Example
48
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 and how to enumerate items with foreach statement
Microsoft
49