Common ASP.NET Code Techniques (DPC&dwc Reference)

Figure 2.1
Output of Listing 2.1.1 when viewed through a browser.

Adding Elements to an ArrayList
In Listing 2.1.1 we create two ArrayList class instances, aTerritories and aStates, on lines 5 and 6, respectively. We then populate the aStates ArrayList with a small subset of the 50 states of the United States using the Add method (lines 9 through 13). The Add method takes one parameter, the element to add to the array, which needs to be of type Object. This Object instance is then appended to the end of the ArrayList. In this example we are simply adding elements of type String to the ArrayList aStates and aTerritories.

The Add method is useful for adding one element at a time to the end of the array, but what if we want to add a number of elements to an ArrayList at once? The ArrayList class provides the AddRange method to do just this. AddRange expects a single parameter that supports the ICollection interface. A wide number of .NET Framework classes—such as the Array, ArrayList, DataView, DataSetView, and others—support this interface. On line 18 in Listing 2.1.1, we use the AddRange method to add each element of the aStates ArrayList to the end of the aTerritories ArrayList. (To add a range of elements starting at a specific index in an ArrayList, use the InsertRange method.) On lines 18 and 19, we add two more strings to the end of the aTerritories ArrayList.

Because ArrayLists are ordered sequentially, there might be times when we want to add an element to a particular position. The Insert method of the ArrayList class provides this capability, allowing the developer to add an element to a specific spot in the ArrayList collection. The Insert method takes two parameters: an integer representing the index in which you want to add the new element, and the new element, which needs to be of type Object. In line 23 we add a new string to the start of the aTerritories ArrayList. Note that if we had simply used the Add method, "District of Columbia" would have been added to the end of aTerritories. Using Insert, however, we can specify exactly where in the ArrayList this new element should reside.

Removing Elements from an ArrayList
The ArrayList class also provides a number of methods for removing elements. We can remove a specific element from an ArrayList with the Remove method. On line 37 we remove the String "Wyoming" from the aTerritories ArrayList. (If you attempt to remove an element that does not exist, an ArgumentException exception will be thrown.) Remove allows you to take out a particular element from an ArrayList; RemoveAt, used on line 40, allows the developer to remove an element at a specific position in the ArrayList.

Both Remove and RemoveAt dissect only one element from the ArrayList at a time. We can remove a chunk of elements in one fell swoop by using the RemoveRange method. This method expects two parameters: an index to start at and a count of total elements to remove. In line 56 we remove the first two elements in aTerritories with the statement: aTerritories.RemoveRange(0, 2). Finally, to remove all the contents of an ArrayList, use the Clear method (refer to Line 69 in Listing 2.1.1).

Referencing ArrayList Elements
Note that in our code example, we used two different techniques to iterate through the contents of our ArrayList. Because an ArrayList stores items sequentially, we can iterate through an ArrayList by looping from its lowest bound through its upper bound, referencing each element by its integral index. The following code snippet is taken from lines 30 through 33 in Listing 2.1.1:

For i = 0 to aTerritories.Count - 1
  lblTerritories.Text = lblTerritories.Text & _
             aTerritories(i) & "<br>"
The Count property returns the number of elements in our ArrayList. We start our loop at 0 because all collections are indexed starting at 0. We can reference an ArrayList element with: aArrayListInstance(index), as we do on line 32 in Listing 2.1.1.

We can also step through the elements of any of the collection types we'll be looking at in this chapter using a For Each ... Next loop with VB.NET (or a foreach loop with C#). A simple example of this approach can be seen in the following code snippet from lines 48 through 52:

Dim s as String
For Each s in aTerritories
  lblFewerTerritories.Text = lblFewerTerritories.Text & _
               s & "<br>"
This method is useful for stepping through all the elements in a collection. In the future section "Similarities Among the Collection Types," we'll examine a third way to step through each element of a collection: using an enumerator.

If we wanted to grab a specific element from an ArrayList, it would make sense to reference it in the aArrayListInstance(index) format. If, however, you are looking for a particular element in the ArrayList, you can use the IndexOf method to quickly find its index. For example,

Dim iPos as Integer
iPos = aTerritories.IndexOf("Illinois")
would set iPos to the location of Illinois in the ArrayList aTerritories. (If Illinois did not exist in aTerritories, iPos would be set to -1.) Two other forms of IndexOf can be used to specify a range for which to search for an element in the ArrayList. For more information on those methods, refer to the .NET Framework SDK documentation.

Working with the Hashtable Class
The type of collection most developers are used to working with is the hash table collection. Whereas the ArrayList indexes each element numerically, a hash table indexes each element by an alphanumeric key. The Collection data type in Visual Basic is a hash table; the Scripting.Dictionary object, used commonly in classic ASP pages, is a simple hash table. The .NET Framework provides developers with a powerful hash table class, Hashtable.

When working with the Hashtable class, keep in mind that the ordering of elements in the collection are irrespective of the order in which they are entered. The Hashtable class employs its own hashing algorithm to efficiently order the key/value pairs in the collection. If it is essential that a collection's elements be ordered alphabetically by the value of their keys, use the SortedList class, which is discussed in the next section, "Working with the SortedList Class."

Adding, Removing, and Indexing Elements in a Hashtable
With the ArrayList class, there were a number of ways to add various elements to various positions in the ArrayList. With the Hashtable class, there aren't nearly as many options because there is no sequential ordering of elements. To add new elements to a Hashtable use the Add method.

Not surprisingly, there are also fewer methods to remove elements from a Hashtable. The Remove method dissects a single element, whereas the Clear method removes all elements from a Hashtable. Examples of both of these methods can be seen in Listing 2.1.2. The output is shown in Figure 2.2.

Listing 2.1.2 For Sequentially Accessed Collections, Use the ArrayList
1: <script language="VB" runat="server">
3:  Sub Page_Load(sender as Object, e as EventArgs)
4:   ' Create a HashTable
5:   Dim htSalaries As New Hashtable()
7:   ' Use the Add method to add Employee Salary Information
8:   htSalaries.Add("Bob", 40000)
9:   htSalaries.Add("John", 65000)
10:   htSalaries.Add("Dilbert", 25000)
11:   htSalaries.Add("Scott", 85000)
12:   htSalaries.Add("BillG", 90000000)
14:   ' Now, display a list of employees and their salaries
15:   lblSalary.Text = "<i>There are " & htSalaries.Count & _
16:           " Employees...</i><br>"
18:   Dim s as String
19:   For Each s in htSalaries.Keys
20:    lblSalary.Text &= s & " - " & htSalaries(s) & "<br>"
21:   Next
23:   ' Is BillG an Employee? If so, FIRE HIM!
24:   If htSalaries.ContainsKey("BillG") Then
25:    htSalaries.Remove("BillG")
26:   End If
29:   ' List the remaining employees (using databinding)
30:   dgEmployees.DataSource = htSalaries.Keys
31:   dgEmployees.DataBind()
34:   htSalaries.Clear() ' remove all entries in hash table...
35:  End Sub
37: </script>
39: <html>
40: <body>
41:  <b>Employee Salary Information:</b><br>
42:  <asp:label id="lblSalary" runat="server" />
43:  <p>
45:  <b>Remaining Employees After Round One of Firings:</b><br>
46:  <asp:datagrid runat="server" id="dgEmployees"
47:         AutoGenerateColumns="True" ShowHeader="False"
48:         CellSpacing="1" CellPadding="4" />
49: </body>
50: </htm


Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >



如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。