首页 >> XML/WebService >> 正文
Common ASP.NET Code Techniques (DPC&DWC Reference)--3
  来源:本站整理 作者:佚名 时间:2005-6-10  

Figure 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><br>"
16:   Dim dictEntry as DictionaryEntry
17:   For Each dictEntry in slTestScores
18:    lblScores.Text &= dictEntry.Key & " - " & dictEntry.Value & "<br>"
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))
& "<br>"
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><br>
49:  <asp:label id="lblScores" runat="server" />
50:  <p>
51:
52:  <b>Curved Test Results:</b><br>
53:  <asp:label id="lblCurvedScores" runat="server" />
54: </body>
55: </html>


上一篇:Common ASP.NET Code Techniques (DPC&DWC Reference)--4 下一篇:如何在DataGrid控件中隐藏列

本篇新闻:Common ASP.NET Code Techniques (DPC&DWC Reference)--3

相关新闻
相关评论
 
评论表单加载中...
 
XML/WebService文章

 在Visual C++应

 编辑:admin

 时间:2008-3-10


   编程入门网-介绍.NET中的委派(Delegates)之三
   编程入门网-介绍.NET中的委派(Delegates)之二
   编程入门网-介绍.NET中的委派(Delegates)之一
   编程入门网-用Visual C#实现文件下载功能
   编程入门网-用C#写简单的CGI程式
最新文章
   编程入门网-介绍.NET中的委派(Delegates)之三
   编程入门网-介绍.NET中的委派(Delegates)之二
   编程入门网-介绍.NET中的委派(Delegates)之一
   编程入门网-用Visual C#实现文件下载功能
   编程入门网-用C#写简单的CGI程式
总站搜索
搜索
 
热门文章
   oracle数据库文件中的导入\导出
   用Oracle10g列值掩码技术隐藏敏感数据
   VB程序中用ADO对象动态创建数据库和表-VB.NET
   用VB6写简单程序 让电骡自动关机-VB.NET
   使用.NET2.0编写COM组件供VB调用-VB.NET
   VB.NET:键盘控制焦点移动-VB.NET
   用VB.NET绘制GDI图形-VB.NET
   vb.net中应用 ArrayList 实例-VB.NET
 
推荐文章
ASP.NET中的状态管理-ASP.NET
VC、IE、ASP环境下打印、预备的完美解决方案
oracle数据库文件中的导入\导出
VB.NET中快速访问注册表技巧-VB.NET
在vb中实现超连接的方法!和直接发邮件-VB.NET
用VB做realplayer播放列表-VB.NET
在VB.NET中如何实现和利用SortedLists-VB.NET
利用VB.NET Stopwatch对象记录时间-VB.NET
成都古羌科技有限公司版权所有: Copyright@2007-2010 ,ALL Rights Reserved 蜀ICP备07017240号