Tài liệu Module 7: Strings, Arrays, and Collections pdf

70 326 0
Tài liệu Module 7: Strings, Arrays, and Collections pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Module 7: Strings, Arrays, and Collections Contents Overview Strings Terminology – Collections 20 NET Framework Arrays 21 NET Framework Collections 39 Lab 7: Working with Strings, Enumerators, and Collections 57 Review 63 Information in this document, including URL and other Internet Web site references, is subject to change without notice Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred Complying with all applicable copyright laws is the responsibility of the user Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property  2001-2002 Microsoft Corporation All rights reserved Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries The names of actual companies and products mentioned herein may be the trademarks of their respective owners Module 7: Strings, Arrays, and Collections iii Instructor Notes Presentation: 120 Minutes After completing this module, students will be able to: ! Parse, format, manipulate, and compare strings ! Use the classes in the System.Array and System.Collections namespaces ! Lab: 60 Minutes Improve the type safety and performance of collections by using specialized collections and class-specific code Materials and Preparation This section provides the materials and preparation tasks that you need to teach this module Required Materials To teach this module, you need the Microsoft® PowerPoint® file 2349B_07.ppt Preparation Tasks To prepare for this module, you should: ! Read all of the materials for this module ! Practice the demonstrations ! Complete the lab iv Module 7: Strings, Arrays, and Collections Demonstrations This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes Sorting and Enumerating an Array In this demonstration, you will show students how to sort and enumerate an array The code for this demonstration is contained in one project and is located in \Democode\Mod07\Demo07.1 In addition, the code for the individual demonstration is provided in the student notes ArrayList In this demonstration, you will show students how ArrayList implements the IList interface by using an array whose size is dynamically increased as required The code for this demonstration is contained in one project and is located in \Democode\Mod07\Demo07.2 In addition, the code for the individual demonstration is provided in the student notes Hashtable In this demonstration, you will show students how to create a hash table that is used for searches The code for this demonstration is contained in one project and is located in \Democode\Mod07\Demo07.3 In addition, the code for the individual demonstration is provided in the student notes In all of the preceding demonstrations, use the debugger to step through the code while you point out features Module 7: Strings, Arrays, and Collections Module Strategy Use the following strategy to present this module: ! Strings Discuss how to work with strings in the Microsoft NET Framework, including common operations, such as parsing, formatting, manipulating, and comparing strings ! Terminology – Collections Define the term collection as it is used in this module and identify where collections are found in the NET Framework Be sure that students understand that the term collection is used in its broader sense: to describe a group of items ! NET Framework Arrays Introduce the System.Array class as the base class of all array types that contains methods for creating, manipulating, searching, and sorting arrays Discuss features of arrays that are specific to C# Explain the role of the IEnumerable and IEnumerator interfaces in System.Array and System.Collections classes Use the Sorting and Enumerating an Array demonstration to show how to sort and enumerate an array ! NET Framework Collections Briefly introduce some commonly used classes in the System.Collections namespace Discuss the IList interface with regards to classes that represent an ordered collection of objects that can be individually indexed Use the ArrayList demonstration to reinforce this concept Discuss the IDictionary interface and the classes that it implements Use the Hashtable demonstration to show how to use the IDictionary interface Provide guidelines to help students distinguish between collections and arrays, and explain when collections are used Discuss runtime casting for type safety and the effects of runtime casting, and boxing and unboxing on performance Discuss techniques for handling boxing and unboxing to optimize performance v Module 7: Strings, Arrays, and Collections Overview Topic Objective To provide an overview of the module topics and objectives ! ! NET Framework Arrays ! In this module, you will learn about some of the key classes in the NET Framework class library Terminology – Collections ! Lead-in Strings NET Framework Collections *****************************ILLEGAL FOR NON-TRAINER USE****************************** In this module, you will learn about some of the key classes in the Microsoft® NET Framework class library Specifically, you will learn how to work with strings, arrays, collections, and enumerators After completing this module, you will be able to: ! Parse, format, manipulate, and compare strings ! Use the classes in the System.Array and System.Collections namespaces ! Improve the type safety and performance of collections by using specialized collections and class-specific code Module 7: Strings, Arrays, and Collections " Strings Topic Objective To introduce the topics in the section ! Parse Lead-in ! Format ! Format Examples ! Changing Case ! Compare ! Trim and Pad ! Split and Join ! StringBuilder ! C# Specifics ! Regular Expressions In this section, you will learn how to work with strings in the NET Framework *****************************ILLEGAL FOR NON-TRAINER USE****************************** In the C# language, string is an alias for System.String in the NET Framework The System.String type represents a string of Unicode characters Working with strings is an everyday task in software development, and includes operations, such as parsing, formatting, manipulating, and comparing strings The String object is immutable Therefore, every time you use one of the methods in the System.String class, you create a new string object When you want to perform repeated modifications to a string, the overhead that is associated with creating a new String object can be costly As an alternative, you can use the System.Text.StringBuilder class to modify a string without creating a new object In this section, you will learn how to work with strings in the NET Framework Module 7: Strings, Arrays, and Collections Parse Topic Objective ! To explain how the Parse method is used to convert numeric strings to a NET Framework numeric base type Parse Method Converts a Numeric String to a Numeric string MyString = "12345"; string MyString = "12345"; int MyInt = int.Parse(MyString); int MyInt = int.Parse(MyString); MyInt++; MyInt++; Console.WriteLine(MyInt); Console.WriteLine(MyInt); // The output to the console is "12346" // The output to the console is "12346" Lead-in The Parse method converts a string that represents a NET Framework numeric base type to an actual NET Framework numeric base type ! To Ignore Commas, Use the NumberStyles.AllowThousands Flag string MyString = "123,456"; string MyString = "123,456"; int MyInt = int.Parse(MyString, int MyInt = int.Parse(MyString, System.Globalization.NumberStyles.AllowThousands); System.Globalization.NumberStyles.AllowThousands); Console.WriteLine(MyInt); Console.WriteLine(MyInt); // The output to the console is "123456" // The output to the console is "123456" *****************************ILLEGAL FOR NON-TRAINER USE****************************** The Parse method converts a string that represents a NET Framework numeric base type to an actual NET Framework numeric base type The Parse method takes a combination of up to three parameters, as follows: ! The string to be converted ! One or more values from the System.Globalization.NumberStyles enumeration ! A NumberFormatInfo class Because the Parse method assumes that all string input represents a base-10 value, non-base-10 values are not parsable The Parse method also does not parse strings that represent the values NaN (Not A Number), PositiveInfinity, or NegativeInfinity of the Single and Double classes because they are not real numbers The following code example converts a string to an int value, increments that value, and displays the result: string MyString = "12345"; int MyInt = int.Parse(MyString); MyInt++; Console.WriteLine(MyInt); // The output to the console is "12346" Module 7: Strings, Arrays, and Collections Handling Nonnumeric Characters The NumberStyles enumeration is useful if you have a string that contains nonnumeric characters that you want to convert into a NET Framework numeric base type You must use this enumeration to parse a string with a currency symbol, decimal point, exponent, parentheses, and so on For example, a string that contains a comma cannot be converted to an int value by using the Parse method unless you pass the System.Globalization.NumberStyles enumeration Incorrect Way to Parse a String with Nonnumeric Characters The following code example is invalid and raises an exception It illustrates the incorrect way to parse a string that contains nonnumeric characters string MyString = "123,456"; // the following line raises a System.Format exception int MyInt = int.Parse(MyString); Console.WriteLine(MyInt); Correct Way to Parse a String with Nonnumeric Characters When you apply the System.Globalization.NumberStyles enumeration with the AllowThousands flag, the Parse method ignores the comma that raised the exception in the preceding example The following code example uses the same string as the preceding example but does not raise an exception string MyString = "123,456"; int MyInt = int.Parse(MyString, System.Globalization.NumberStyles.AllowThousands); Console.WriteLine(MyInt); // The output to the console is "123456" 50 Module 7: Strings, Arrays, and Collections SortedList Topic Objective To explain how arrays are used in a SortedList and how to create, initialize, and access a SortedList This topic is very important because its contents are required for the lab Lead-in A SortedList maintains two arrays internally to store entries to the list: one array for the keys, and another array for the associated values ! SortedList Maintains Two Arrays for Entries # One array for the keys and another array for the associated values SortedList mySL = new SortedList(); SortedList mySL = new SortedList(); // Add an entry with a key = "First" and a value = // Add an entry with a key = "First" and a value = mySL.Add("First", 1); mySL.Add("First", 1); // Increment the value of the entry whose key = "First" // Increment the value of the entry whose key = "First" mySL["First"] = (Int32)mySL["First"] + 1; mySL["First"] = (Int32)mySL["First"] + 1; ! Count Property – Number of Elements in the SortedList ! Sorted Using a Specific IComparer Implementation or According to the Key's IComparable Implementation ! Printing the Keys and Values of a SortedList for ( int i = 0; i < myList.Count; i++ ) { for ( int i = 0; i < myList.Count; i++ ) { Console.WriteLine( "\t{0}:\t{1}", Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) ); } myList.GetKey(i), myList.GetByIndex(i) ); } *****************************ILLEGAL FOR NON-TRAINER USE****************************** A SortedList maintains two arrays internally to store entries to the list: one array for the keys, and another array for the associated values An entry is a key-and-value pair A SortedList implements the IDictionary, IEnumerable, ICollection, and ICloneable interfaces The Count property gets the number of elements that are contained in the SortedList The Add method is used to add an entry to the SortedList The [ ] Operator is used to modify the value of an entry with the specified key For Your Information You should carefully cover the SortedList class, the Add method, and the [ ] Operator because they are used in the lab You can sort the keys of a SortedList according to an IComparer implementation that is specified when the SortedList is instantiated or according to the IComparable implementation that is provided by the keys themselves In either case, a SortedList does not allow duplicate keys Operations on a SortedList tend to be slower than operations on a Hashtable because of the sorting However, the SortedList offers more flexibility by allowing access to the values through the associated keys or through the indexes A key cannot be a null reference, but a value can be a null reference Indexes in the SortedList collection are zero-based Module 7: Strings, Arrays, and Collections 51 The following example shows how to create a SortedList, add an entry, modify an entry’s value, and print out the SortedList’s keys and values using System; using System.Collections; public class SamplesSortedList public static void Main() { { // Create and initialize a new SortedList SortedList mySL = new SortedList(); mySL.Add("First", 1); mySL.Add("Second", 2); mySL.Add("Third", 3); // Display the properties and values of the SortedList Console.WriteLine( "mySL" ); Console.WriteLine( " Count: {0}", mySL.Count ); Console.WriteLine( " Capacity: {0}", mySL.Capacity ); Console.WriteLine( " Keys and Values:" ); PrintKeysAndValues( mySL ); // increment the value of the entry whose key is "Third" mySL["Third"] = (Int32)mySL["Third"] + 1; PrintKeysAndValues( mySL ); } public static void PrintKeysAndValues( SortedList myList ){ Console.WriteLine( "\t-KEY-\t-VALUE-" ); for ( int i = 0; i < myList.Count; i++ ) { Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) ); } Console.WriteLine(); } } The preceding code example displays the following output to the console: mySL Count: Capacity: 16 Keys and Values: -KEY-VALUEFirst: Second: Third: -KEYFirst: Second: Third: -VALUE1 52 Module 7: Strings, Arrays, and Collections Collection Usage Guidelines Topic Objective To distinguish between collections and arrays and explain when collections are used ! Use a Collection instead of an Array: # Lead-in Arrays and collections are used similarly, but they perform differently # ! When Add, Remove, or other methods for manipulating the set of objects are supported This scopes all related methods to the collection When you want to provide a read-only set of objects System.Array objects are always writable - You can add read-only wrappers around internal arrays Use Collections to Avoid Inefficiencies # In the following code, each call to the myObj property creates a copy of the array As a result, 2n+1 copies of the array are created: for (int i = 0; i < obj.myObj.Count; i++) for (int i = 0; i < obj.myObj.Count; i++) DoSomething(obj.myObj[i]); DoSomething(obj.myObj[i]); *****************************ILLEGAL FOR NON-TRAINER USE****************************** Class library designers sometimes need to decide when to use an array and when to use a collection Arrays and collections have similar usage models, but they differ somewhat in performance Collections vs Arrays When Add, Remove, or other methods for manipulating the collection are supported, use a collection, instead of an array Using a collection scopes all related methods to the collection Also, use collections to add read-only wrappers around internal arrays System.Array objects are always writable Array Valued Properties Use collections to avoid code inefficiencies In the following code example, each call to the myObj property creates a copy of the array As a result, 2n+1 copies of the array will be created in the following loop: for (int i = 0; i < obj.myObj.Count; i++) DoSomething(obj.myObj[i]); Module 7: Strings, Arrays, and Collections 53 Choosing A Collection Class Choosing the right Collections class must be done carefully Using the wrong collection can unnecessarily restrict how you use it Consider the following questions: ! Do you need temporary storage? • If yes, consider Queue or Stack • If no, consider the other collections ! Do you need to access the elements in a certain order, such as first-in-firstout, last-in-first-out, or randomly? • The Queue offers first-in, first-out access • The Stack offers last-in, first-out access • The rest of the collections offer random access ! Do you need to access each element by index? • ArrayList and StringCollection offer access to their elements by the zero-based index • Hashtable, SortedList, ListDictionary, and StringDictionary offer access to their elements by the key of the element • NameObjectCollectionBase and NameValueCollection offer access to their elements either by the zero-based index or by the key of the element ! Will each element contain just one value or a key-singlevalue pair or a keymultiplevalues combination? • One value: Use any of the collections based on IList • Key-singlevalue pair: Use any of the collections based on IDictionary • Key-multiplevalues combination: Consider using or deriving from the NameValueCollection class in the Collections.Specialized namespace ! Do you need to sort the elements differently from how they were entered? • Hashtable sorts the elements by the hash code of the key • SortedList sorts the elements by the key, based on an IComparer implementation • ArrayList provides a Sort method that takes an IComparer implementation as a parameter ! Do you need fast searches and retrieval of information? • ListDictionary is faster than Hashtable for small collections of ten items or less ! Do you need collections that accept only strings? • StringCollection (based on IList) and StringDictionary (based on IDictionary) are in the Collections.Specialized namespace 54 Module 7: Strings, Arrays, and Collections Type Safety and Performance Topic Objective ! System.Collections Items Require a Runtime Object Cast ! To discuss runtime casting for type safety and the effects of runtime casting and boxing and unboxing on performance Drawbacks of Runtime Casting # # ! The System.Collections classes are generic collections, which ignore their items’ true types Generic collections allow classes to be used for items of any type Runtime overhead of casting # Lead-in Type errors found at runtime, rather than at compile time Runtime overhead of boxing/unboxing operations for value types Type-Specific Collection Classes Can Eliminate Runtime Casting # # ! System.Collections.Specialized namespace contains stringspecific collections Create your own type-specific collection class by inheriting from a System.Collections class and adding type-specific members Ways to Reduce Boxing and Unboxing Operations of Value Types # Encapsulate value types in a class # Manipulate value types through interfaces *****************************ILLEGAL FOR NON-TRAINER USE****************************** The System.Collections classes are generic collections, which ignore their items’ true types Generic collections allow classes to be used for items of any type Drawbacks of Runtime Casting The System.Collections classes have properties and methods that manipulate the collection’s items through the item’s System.Object base type The class’s members take and return parameters of type System.Object For example, IEnumerator.Current returns a System.Object instance This use of an object’s base class requires casting a runtime object to obtain the true type of the object Casting System.Object instances at run time has two drawbacks: ! Collection operations with invalid parameter or return types are not flagged at compile time If the cast is invalid, the problem is only detected at run time when an InvalidCastException is thrown ! Such casting hurts runtime performance because the NET runtime must perform type-checking In addition, in the case of a collection of value types, such as an int, casting to and from System.Object results in boxing and unboxing operations that further impair performance The ideal solution to these two drawbacks would be a language mechanism that automatically generates a type-specific version of the System.Collections classes that is similar to the C++ template class mechanism For example, if you declared an ArrayList, this object would store int values directly, without casting and without boxing This feature is not implemented in the first version of C#; however, it may be implemented in a later version Module 7: Strings, Arrays, and Collections 55 The System.Collections classes provide a simple and powerful way to implement collections Carefully evaluate whether the use of these classes in your programs imposes a significant enough performance penalty to warrant taking the further action that is described in the following sections Strongly-Typed Collections One way to provide compile-time type-checking and improve the performance of collection code is to use strongly-typed collections The System.Collections.Specialized namespace contains string-specific collection classes, as described in the following table Class Description NameValueCollection Represents a sorted collection of associated String keys and String values that can be accessed with the hash code of the key or with the index StringCollection Represents a collection of strings StringDictionary Implements a hash table with the key strongly-typed to be a string, rather than an object StringEnumerator Supports a simple iteration over a StringCollections Creating Custom Collection Classes You can also create your own strongly-typed collection by creating your own custom collection class Your class can reuse System.Collections functionality by inheriting from the appropriate System.Collections class You create the type-specific class with methods and properties whose parameters and return types are type-specific By using C#’s explicit interface implementation mechanism, which is discussed in Module 6, “Working with Types,” in Course 2349B, Programming with the Microsoft NET Framework (Microsoft Visual C#™ NET), a class can implement both non-interface and interface members of the same name Explicit interface method implementations are frequently used when you implement such interfaces as IEnumerable, IEnumerator, ICloneable, IComparable, ICollection, IList, and IDictionary By having both sets of members, clients that expect type-specific or System.Object parameters and return values can use the custom class Techniques for Handling Boxing and Unboxing Instead of creating a type-specific collection class, you can remove the overhead of boxing and unboxing by using a reference type, rather than a value type, for the items in a collection To accomplish this, you can wrap a value type in a class, as shown in Module 6, Course 2349B, Programming with the Microsoft NET Framework (Microsoft Visual C# NET) In some cases, you can reduce boxing and unboxing by using interfaces Value types can implement interfaces, but because interfaces are referenced types, you can only have an interface reference to a boxed value type You can define an interface for your value type that has the methods and properties that are needed to manipulate the value type The value type instance must still be boxed when it is inserted into a generic System.Collections object, but your code will be able to manipulate the item’s value through its interface without unboxing the item 56 Module 7: Strings, Arrays, and Collections For example, in the case of a collection of integer values where you want to be able to add an integer to an element’s value, you can have your value type implement an interface, as in the following code: interface IAdd { void Add(int amount); } struct IntStruct: IAdd { int number; public IntStruct(int number) { this.number = number; } public int Number { get { return(number);} } public void Add(int amount) { number += amount; } public override string ToString() { return(number.ToString()); } } Module 7: Strings, Arrays, and Collections 57 Lab 7: Working with Strings, Enumerators, and Collections *****************************ILLEGAL FOR NON-TRAINER USE****************************** Objectives After completing this lab, you will be able to: ! Create an application that parses and formats strings ! Create an application that uses SortedList collection objects Lab Setup Starter and solution files are associated with this lab The starter files are in the folder \Labs\Lab07\Starter, and the solution files are in the folder \Labs\Lab07\Solution Scenario In this lab, you are provided with a Visual Studio NET console application as a starting point The application, named WordCount, parses a test string into words and then determines the number of unique words and the number of times each word occurs The results of this analysis are formatted and displayed on the console The application is a modified version of the NET Framework SDK sample, Word Count Estimated time to complete this lab: 60 minutes 58 Module 7: Strings, Arrays, and Collections Exercise Sorting Words Alphabetically In this exercise, you will create a class that breaks up the test string into words and then stores each word and the number of its occurrences in a SortedList By default, the sort order will be based on the alphabetical ordering of the word keys ! Modify the WordCount class to sort words alphabetically Open the WordCount project in the starter directory by using Visual Studio NET Open the WordCount.cs file In the WordCounter class, create a member named wordCounter that is an instance of the SortedList class Create a read-only property named UniqueWords that returns the number of items in wordCounter Create a public method named GetWordsAlphabeticallyEnumerator that takes no arguments and returns a wordCounter enumerator object of type IDictionaryEnumerator Create a public method named CountStats that takes two out parameters of type Int64 named numWords and numChars and returns a Boolean Implement the CountStats method to break up the test string, create the alphabetically sorted list, and return the word count statistics a Initialize the CountStats method’s out parameters to b Use the String.Split method to break up testString into individual words that are stored in an array of type string named Words c Assign to the out parameter numWords the number of words that are obtained in step 7.b d For each non-empty string in the array Words: i Add the number of characters in the word string to numChars ii If wordCounter does not already contain the string, add a new entry whose key is the string and whose value is The value represents the number of occurrences of the word Otherwise, increment by one the value of the existing entry Tip For information about and examples of the IDictionary methods named Add and Contains, see Dictionaries and Demonstration: Hashtable in this module For an example of how to modify the value of an entry by using the [] Operator, see SortedList in this module iii Return true Module 7: Strings, Arrays, and Collections 59 ! Modify the Application class In the Application class's Main method, create an instance of WordCounter named wc Create two variables of type Int64 named NumWords and NumChars Call the wc object’s CountStats method to assign the word and character counts to NumWord and NumChars respectively Output to the console the test string WordCounter.testString Output to the console a two-column header labeled Words and Chars Use a tab to separate the columns Output to the console the number of words, and format this output to occupy five characters, followed by a tab and the number of characters ! Test the WordCount application • Build and run the application You should see output that is similar to the following: For string Hello world hello here Words 11 Chars 41 i am where are you hello you 60 Module 7: Strings, Arrays, and Collections Exercise Sorting Words by Number of Occurrences In this exercise, you will create a nested class that implements the IComparable interface and whose CompareTo method will result in a SortedList that is ordered on the basis of the number of occurrences of a word ! Modify the WordCount class to sort words by occurrences Add a nested class named WordOccurrence that inherits from IComparable Add a private member of type int named occurrences Add a private member of type String named word Add a constructor that takes two parameters The first parameter is of type int, and the second parameter is of type String The constructor assigns the first value to occurrences and the second value to word Add a public method CompareTo that takes an Object parameter and returns an int The code should follow the CompareTo design pattern and return a value that results in a sort of words that is ordered by the occurrences of each word in ascending order Less frequently occurring words should be followed by more frequently occurring words In the case in which the number of occurrences of the instance and the Object parameter are the same, the sort should be alphabetical by using the String.Compare method Tip For an example of implementing the CompareTo method, see Demonstration: Sorting and Enumerating an Array in this module Add two public read-only properties named Occurrences and Word that return the fields occurrences and word respectively End the nested class definition Back in the WordCounter class itself, add a public method named GetWordsByOccurrenceEnumerator that returns an object of type IDictionaryEnumerator Implement GetWordsByOccurrenceEnumerator as follows: a Create a new SortedList named sl b Iterate through the alphabetically-sorted list named wordCounter by using an enumerator that is obtained by calling the GetWordsAlphabeticallyEnumerator method i For each alphabetical list entry, create a new object of type WordOccurence that is initialized with the alphabetically sorted list entry’s Value and Key ii Add to sl a new entry whose key field is the new WordOccurence object and whose value field is set to null c Return an enumerator of sl of type IDictionaryEnumerator Module 7: Strings, Arrays, and Collections 61 ! Modify the Application class Output the words to be sorted alphabetically by adding code to the Application class’s Main method to: a Obtain an IDictionaryEnumerator object named de by calling the wc object’s GetWordsAlphabeticallyEnumerator method b Display a message to inform the user that the output that is generated will display word usage sorted alphabetically Also inform the user of the number of unique words c Iterate over the collection and output each entry’s value and key, formatting them so that the value is displayed in the first column and the key is displayed in the second column Output the words sorted by occurrence by adding code to: a Assign to de an IDictionaryEnumerator object by calling the wc object’s GetWordsByOccurrenceEnumerator method b Display a message to inform the user that the output that is generated will display word usage sorted by occurrence Also inform the user of the number of unique words c Iterate over the collection For each entry, obtain the key field’s WordCounter.WordOccurrence object and output to the console the Occurrences property of the WordCounter.WordOccurrence object in the first column and the object’s Word property in the second column 62 Module 7: Strings, Arrays, and Collections ! Test the WordCount application • Build and run the application You should see output that is similar to the following: For string Hello world hello here i am where are you hello you Words Chars 11 41 Word usage sorted alphabetically (9 unique words) 1: "am" 1: "are" 2: "hello" 1: "Hello" 1: "here" 1: "i" 1: "where" 1: "world" 2: "you" Word usage sorted by occurrence (9 unique words) 1: am 1: are 1: Hello 1: here 1: i 1: where 1: world 2: hello 2: you Module 7: Strings, Arrays, and Collections 63 Review Topic Objective To reinforce module objectives by reviewing key points Lead-in The review questions cover some of the key concepts taught in the module ! Strings ! Terminology – Collections ! NET Framework Arrays ! NET Framework Collections *****************************ILLEGAL FOR NON-TRAINER USE****************************** Enter the code to read an integer from the console and assign it to a variable named aNumber int MyInt = int.Parse(Console.ReadLine()); What class should you use to improve performance when you want to perform repeated modifications to a string? System.Text.StringBuilder Name and briefly describe the interfaces implemented by System.Array ICloneable: Supports cloning, which creates a new instance of a class with the same value as an existing instance IList: Represents a collection of objects that can be individually indexed ICollection: Defines size, enumerators, and synchronization methods for all collections IEnumerable: Exposes the enumerator, which supports a simple iteration over a collection What does it mean to say that an enumerator is required to be safe? The enumerator must have a fixed view of the items in a collection that remains the same, even if the collection is modified 64 Module 7: Strings, Arrays, and Collections Create an array that contains the integers 1, 2, and Then use the C# foreach statement to iterate over the array and output the numbers to the console int[ ] numbers = {1, 2, 3}; foreach (int i in numbers) { System.Console.WriteLine("Number: {0}", i); } What is the name of the interface that is implemented by classes that contain an ordered collection of objects that can be individually indexed? Name the System.Collections classes that implement this interface The IList interface is implemented by Array, ArrayList, StringCollection, and TreeNodeCollection What is the name of the interface for collections of associated keys and values? Name the System.Collections classes that implement this interface The IDictionary interface is implemented by Hashtable, DictionaryBase, and SortedList Generic collection classes require runtime type-casting of their items to obtain the true type of the items in the collection classes Name the issues raised by runtime casting Type-checking cannot be done at compile time Performance overhead of casting In the case of collection of value types, boxing and unboxing operations ... documentation 20 Module 7: Strings, Arrays, and Collections Terminology – Collections Topic Objective To define the term collection as it is used in this module and to identify where collections are... array 26 Module 7: Strings, Arrays, and Collections Declaring an Array C# supports single-dimensional arrays and multidimensional arrays, which are also know as rectangular arrays, and jagged... yyyy f Full date and time (long date and short time) Dd MMMM yyyy FullDateTimePattern (long date and long time) Dd MMMM yyyy F HH:mm HH:mm:ss Module 7: Strings, Arrays, and Collections The following

Ngày đăng: 21/12/2013, 05:18

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan