Common ASP.NET Code Techniques (DPC&DWC Reference)--3

80酷酷网    80kuku.com

  asp.netFigure 2.2
Output of Listing 2.1.2 when viewed through a browser.

Adding Elements to a Hashtable
In Listing 2.1.2, we begin by creating an instance of the Hashtable class, htSalaries, on line 5. Next, we populate this hash table with our various employees and their respective salaries on lines 7 through 12. Note that the Add method, which adds an element to the Hashtable collection, takes two parameters: the first is an alphanumeric key by which the element will be referenced, and the second is the element itself, which needs to be of type Object.

In Listing 2.1.2, we are storing integer values in our Hashtable class. Of course we are not limited to storing just simple data types; rather, we can store any type of Object. As we'll see in an example later in this chapter, we can even create collections of collections (collections whose elements are also collections)!

Removing Elements from a Hashtable
The Hashtable class contains two methods to remove elements: Remove and Clear. Remove expects a single parameter, the alphanumeric key of the element to be removed. Line 25 demonstrates this behavior, removing the element referred to as "BillG" in the hash table. On line 34 we remove all the elements of the hash table via the Clear method. (Recall that all collection types contain a Clear method that demonstrates identical functionality.)

The Hashtable class contains two handy methods for determining whether a key or value exists. The first function, ContainsKey, takes a single parameter, the alphanumeric key to search for. If the key is found within the hash table, ContainsKey returns True. If the key is not found, ContainsKey returns False. In Listing 2.1.2, this method is used on line 24. The Hashtable class also supports a method called ContainsValue. This method accepts a single parameter of type Object and searches the hash table to see if any element contains that particular value. If it finds such an element, ContainsValue will return True; otherwise, it will return False. The ContainsKey and ContainsValue methods are used primarily for quickly determining whether a particular key or element exists in a Hashtable.

On line 24, a check was made to see if the key "BillG" existed before the Remove method was used. Checking to make sure an item exists before removing it is not required. If you use the Remove method to try to remove an element that does not exist (for example, if we had Remove("Homer") in Listing 2.2.1), no error or exception will occur.

The Keys and Values Collections
The Hashtable class exposes two collections as properties: Keys and Values. The Keys collection is, as its name suggests, a collection of all the alphanumeric key values in a Hashtable. Likewise, the Values collection is a collection of all the element values in a Hashtable. These two properties can be useful if you are only interested in, say, listing the various keys.

On line 30 in Listing 2.1.2, the DataSource property of the dgEmployees DataGrid is set to the Keys collection of the hySalaries Hashtable instance. Because the Keys property of the Hashtable class returns an ICollection interface, it can be bound to a DataGrid using data binding. For more information on data binding and using the DataGrid, refer to Chapter 7, "Data Presentation."

Working with the SortedList Class
So far we've examined two collections provided by the .NET Framework: the Hashtable class and the ArrayList class. Each of these collections indexes elements in a different manner. The ArrayList indexes each element numerically, whereas the Hashtable indexes each element with an alphanumeric key. The ArrayList orders each element sequentially, based on its numerical index; the Hashtable applies a seemingly random ordering (because the order is determined by a hashing algorithm).

What if you need a collection, though, that allows access to elements by both an alphanumeric key and a numerical index? The .NET Framework includes a class that permits both types of access, the SortedList class. This class internally maintains two arrays: a sorted array of the keys and an array of the values.

Adding, Removing, and Indexing Elements in a SortedList
Because the SortedList orders its elements based on the key, there are no methods that insert elements in a particular spot. Rather, similar to the Hashtable class, there is only a single method to add elements to the collection: Add. However, because the SortedList can be indexed by both key and value, the class contains both Remove and RemoveAt methods. As with all the other collection types, the SortedList also contains a Clear method that removes all elements.

Because a SortedList encapsulates the functionality of both the Hashtable and ArrayList classes, it's no wonder that the class provides a number of methods to access its elements. As with a Hashtable, SortedList elements can be accessed via their keys. A SortedList that stored Integer values could have an element accessed similar to the following:

Dim SortedListValue as Integer
SortedListValue = slSortedListInstance(key)
The SortedList also can access elements through an integral index, like with the ArrayList class. To get the value at a particular index, you can use the GetByIndex method as follows:

Dim SortedListValue as Integer
SortedListValue = slSortedListInstance.GetByIndex(iPosition)
iPosition represents the zero-based ordinal index for the element to retrieve from slSortedListInstance. Additionally, elements can be accessed by index using the GetValueList method to return a collection of values, which can then be accessed by index:

Dim SortedListValue as Integer
SortedListVluae = slSortedListInstance.GetValueList(iPosition)
Listing 2.1.3 illustrates a number of ways to retrieve both the keys and values for elements of a SortedList. The output is shown in Figure 2.3.

Listing 2.1.3 A SortedList Combines the Functionality of a Hashtable and ArrayList
1: <script language="VB" runat="server">
2:  Sub Page_Load(sender as Object, e as EventArgs)
3:   ' Create a SortedList
4:   Dim slTestScores As New SortedList()
5:
6:   ' Use the Add method to add students' Test Scores
7:   slTestScores.Add("Judy", 87.8)
8:   slTestScores.Add("John", 79.3)
9:   slTestScores.Add("Sally", 94.0)
10:   slTestScores.Add("Scott", 91.5)
11:   slTestScores.Add("Edward", 76.3)
12:
13:   ' Display a list of test scores
14:   lblScores.Text = "<i>There are " & slTestScores.Count & _
15:           " Students...</i>
"
16:   Dim dictEntry as DictionaryEntry
17:   For Each dictEntry in slTestScores
18:    lblScores.Text &= dictEntry.Key & " - " & dictEntry.Value & "
"
19:   Next
20:
21:   'Has Edward taken the test? If so, reduce his grade by 10 points
22:   If slTestScores.ContainsKey("Edward") then
23:    slTestScores("Edward") = slTestScores("Edward") - 10
24:   End If
25:
26:   'Assume Sally Cheated and remove her score from the list
27:   slTestScores.Remove("Sally")
28:
29:   'Grade on the curve - up everyone's score by 5 percent
30:   Dim iLoop as Integer
31:   For iLoop = 0 to slTestScores.Count - 1
32:    slTestScores.GetValueList(iLoop) = _
33:           slTestScores.GetValueList(iLoop) * 1.05
34:   Next
35:
36:   'Display the new grades
37:   For iLoop = 0 to slTestScores.Count - 1
38:    lblCurvedScores.Text &= slTestScores.GetKeyList(iLoop) & " - " & _
39:          String.Format("{0:#.#}", slTestScores.GetByIndex(iLoop))
& "
"
40:   Next
41:
42:   slTestScores.Clear() ' remove all entries in the sorted list...
43:  End Sub
44: </script>
45:
46: <html>
47: <body>
48:  <b>Raw Test Results:</b>

49:  <asp:label id="lblScores" runat="server" />
50:  <p>
51:
52:  <b>Curved Test Results:</b>

53:  <asp:label id="lblCurvedScores" runat="server" />
54: </body>
55: </html>

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: