Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
173
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 7: Strings, Arrays, and Collections

39

 

 

 

" .NET Framework Collections

Topic Objective

To introduce the topics in the section.

Lead-in

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, arrays, hashtables, and dictionaries.

!Examples of System.Collections Classes

!Lists

!Dictionaries

!SortedList

!Collection Usage Guidelines

!Type Safety and Performance

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, arrays, hashtables, and dictionaries.

40

Module 7: Strings, Arrays, and Collections

Examples of System.Collections Classes

Topic Objective

To show some of the collection classes in the

System.Collections

namespace.

Lead-in

Let’s look briefly at some of the collection classes in the

System.Collections

namespace.

!ArrayList

#Implements IList by using a dynamically-sized array

!DictionaryBase

#Provides abstract base class for strongly-typed collection of associated keys and values

!Hashtable

#Represents a collection of keys and values that are organized around the key’s hash code

!SortedList

#Represents the collection of keys and values, sorted by keys and accessible by key and index

!BitArray, Queue, Stack, CollectionBase, ReadOnlyCollectionBase

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Do not spend a lot of time on this slide. Just introduce students to some commonly used collection classes and encourage them to refer to the .NET Framework SDK for more information.

The following table shows some of the collection classes in the

System.Collections namespace.

Class

Description

ArrayList

Implements the IList interface by using an array whose

 

size is dynamically increased as required.

BitArray

Manages a compact array of bit values, which are

 

represented as Booleans, where true indicates that the bit

 

is on (1) and false indicates the bit is off (0).

CollectionBase

Provides the abstract base class (MustInherit in

 

Microsoft Visual Basic®) for a strongly-typed collection.

DictionaryBase

Provides the abstract base class (MustInherit in

 

Visual Basic) for a strongly-typed collection of

 

associated keys and values.

Hashtable

Represents a collection of associated keys and values that

 

are organized around the hash code of the key.

Queue

Represents a first-in, first-out collection of objects.

ReadOnlyCollectionBase

Provides the abstract base class (MustInherit in

 

Visual Basic) for a strongly-typed read-only collection.

SortedList

Represents a collection of associated keys and values that

 

are sorted by the keys and are accessible by key and by

 

index.

Stack

Represents a simple last-in-first-out collection of type

 

Object.

Module 7: Strings, Arrays, and Collections

41

 

 

 

Lists

Topic Objective

To describe the public instance members that the IList interface implements.

Lead-in

IList is an interface for classes that represent an ordered collection of objects that can be individually indexed. Array, ArrayList, StringCollection, and TreeNodeCollection are some of the classes that implement IList.

!IList – Interface for Classes That Represent an Ordered Collection of Objects That Can Be Individually Indexed

!Some Classes That Implement IList

#Array, ArrayList, StringCollection, and

TreeNodeCollection

!Methods Include:

#Add, Clear, Contains, Insert, IndexOf, Remove, and

RemoveAt

*****************************ILLEGAL FOR NON-TRAINER USE******************************

IList is an interface for classes that represent an ordered collection of objects that can be individually indexed. Array, ArrayList, StringCollection, and TreeNodeCollection are some of the classes that implement IList.

The following tables describe the public instance properties that the IList interface implements.

Property

Use

 

 

IsFixedSize

When implemented by a class, gets a value indicating whether the IList

 

has a fixed size.

IsReadOnly

When implemented by a class, gets a value indicating whether the IList

 

is read-only.

Item

When implemented by a class, gets or sets the element at the specified

 

index.

 

In C#, this property is the indexer for the IList class.

42

Module 7: Strings, Arrays, and Collections

The following table describes the public instance methods that the IList interface defines.

Method

Use

Add

When implemented by a class, adds an item to the IList.

Clear

When implemented by a class, removes all items from the IList.

Contains

When implemented by a class, determines whether the IList contains a

 

specific value.

IndexOf

When implemented by a class, determines the index of a specific item in

 

the IList.

Insert

When implemented by a class, inserts an item to the IList at the

 

specified position.

Remove

When implemented by a class, removes the first occurrence of a specific

 

object from the IList.

RemoveAt

When implemented by a class, removes the IList item at the specified

 

index.

Module 7: Strings, Arrays, and Collections

43

 

 

 

Demonstration: ArrayList

Topic Objective

To demonstrate how ArrayList implements the IList interface by using an array whose size is dynamically increased as required.

Lead-in

In this demonstration, ArrayList implements the IList interface by using an array whose size is dynamically increased as required.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, ArrayList implements the IList interface by using an array whose size is dynamically increased as required.

using System;

using System.Collections;

class listSample

{

public static void Main(string[] args) { ArrayList fruit = new ArrayList(); fruit.Add("Apple"); fruit.Add("Pear"); fruit.Add("Orange"); fruit.Add("Banana");

Console.WriteLine ("\nList Contains:"); foreach (string item in fruit) {

Console.WriteLine(item);

}

Console.WriteLine (

"\nResult of Contains method for Kiwi: {0}", fruit.Contains("Kiwi"));

Console.WriteLine (

"\nAdding Kiwi at Orange:");

fruit.Insert(fruit.IndexOf("Orange"),"Kiwi"); Console.WriteLine ("\nList Contains:"); foreach (string item in fruit) {

Console.WriteLine(item);

}

(Code continued the following page.)

44

Module 7: Strings, Arrays, and Collections

Console.WriteLine (

"\nResult of Contains method for Kiwi: {0}", fruit.Contains("Kiwi"));

Console.WriteLine (

"\r\nPress Return to exit."); Console.Read();

}

}

The preceding code example displays the following output to the console:

List Contains:

Apple

Pear

Orange

Banana

Result of Contains method for Kiwi: False

Adding Kiwi at Orange:

List Contains:

Apple

Pear

Kiwi

Orange

Banana

Result of Contains method for Kiwi: True

Press Return to exit.

Module 7: Strings, Arrays, and Collections

45

 

 

 

Dictionaries

Topic Objective

To describe the IDictionary interface and the classes that it implements.

Lead-in

IDictionary is an interface for collections of associated keys and values.

!IDictionary is an Interface for Collections of Associated Keys and Values

#Each association must have a unique non-null key, but the value of an association can be any object reference, including a null reference

!Collection Classes That Implement IDictionary Include

#Hashtable, DictionaryBase, and SortedList

!Methods Include:

#Add, Clear, Contains, GetEnumerator, and Remove

*****************************ILLEGAL FOR NON-TRAINER USE******************************

IDictionary is an interface for collections of associated keys and values. Each association must have a unique non-null key, but the value of an association can be any object reference, including a null reference.

Hashtable, DictionaryBase, and SortedList are examples of collection classes that implement IDictionary.

The IDictionary interface allows the contained keys and values in the items in a collection to be enumerated, but it does not imply any particular sort order. The IDictionaryEnumerator interface inherits from IEnumerator and adds members to return the object’s Key and Value fields individually or in a

DictionaryEntry structure.

IDictionary implementations can be divided into the following categories:

!Read-only

You cannot modify a read-only IDictionary.

!Fixed-size

You cannot add or remove elements from a fixed-size IDictionary, but you can modify existing elements.

!Variable-size

You can add, remove, or modify elements in a variable-size IDictionary.

46

Module 7: Strings, Arrays, and Collections

The following table describes some of the public instance properties that the IDictionary interface implements.

Property

Use

IsFixedSize

When implemented by a class, gets a value indicating whether the

 

IDictionary has a fixed size.

IsReadOnly

When implemented by a class, gets a value indicating whether the

 

IDictionary is read-only.

Item

When implemented by a class, gets or sets the element at the

 

specified index.

 

In C#, this property is the indexer for the class.

Keys

When implemented by a class, gets an ICollection containing the

 

keys of the IDictionary.

Values

When implemented by a class, gets an ICollection containing the

 

values in the IDictionary.

The following table describes some of the public instance methods that the IDictionary interface implements.

Method

Use

Add

When implemented by a class, adds an entry with the provided

 

key and value to the IDictionary.

Clear

When implemented by a class, removes all elements from the

 

IDictionary.

Contains

When implemented by a class, determines whether the

 

IDictionary contains an entry with the specified key.

GetEnumerator

When implemented by a class, returns an

 

IDictionaryEnumerator for the IDictionary.

Remove

When implemented by a class, removes the entry with the

 

specified key from the IDictionary.

For a complete list of the members of the IDictionary interface, see “IDictionary Members” in the .NET Framework SDK documentation.

Module 7: Strings, Arrays, and Collections

47

 

 

 

Demonstration: Hashtable

Topic Objective

To demonstrate how to create a hash table that is used for searches.

Lead-in

The Hashtable class represents a collection of associated keys and values that are organized on the basis of the keys’ hash code.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The Hashtable class represents a collection of associated keys and values that are organized on the basis of the keys’ hash code. The objects that are used as keys in a Hashtable must implement or inherit the Object.GetHashCode and Object.Equals methods. If key equality were simply reference equality, the inherited implementation of these methods would suffice.

Furthermore, these methods must produce the same results when they are called with the same parameters while the key exists in the Hashtable. Key objects must be immutable as long as they are used as keys in the Hashtable.

The foreach statement of the C# language requires the type of the elements in the collection. Because each element of the Hashtable is a key-and-value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry, as in the following example:

foreach (DictionaryEntry myEntry in myHashtable) {...}

48

Module 7: Strings, Arrays, and Collections

The code in this demonstration creates a hash table of employee numbers and names, and searches the table for an employee by number and by name.

using System;

using System.Collections;

class HashTableSample

{

public static void Main(String[] args)

{

//create hash table of employee numbers and names Hashtable table = new Hashtable(); table.Add("0123","Jay"); table.Add("0569","Brad"); table.Add("1254","Brian"); table.Add("6839","Seth"); table.Add("3948","Rajesh"); table.Add("1930","Lakshan"); table.Add("9341","Kristian"); printTable(table);

//now we'll look to see if an employee is in the table //by key

Console.Write(

"Search for employee by key, enter ID ==-> "); string input = Console.ReadLine();

if (table.Contains(input)) { Console.WriteLine("Found {0} in the list.",input);

}

else {

Console.WriteLine("Employee {0} not found.",input);

}

//by value Console.Write(

"Search for employee by value, enter name ==-> "); input = Console.ReadLine();

if (table.ContainsValue(input)) { Console.WriteLine("Found {0} in the list.",input);

}

else {

Console.WriteLine("Employee {0} not found.",input);

}

printTable(table);

// remove an employee by key

Console.Write("Remove employee by key, enter ID ==-> "); input = Console.ReadLine();

table.Remove(input);

printTable(table);

Console.WriteLine ("\r\nPress Return to exit."); Console.Read();

}

(Code continued on the following page.)

Соседние файлы в папке c#