Common Code techniques (DPC&DWC Reference)--2

Source: Internet
Author: User
Tags hash insert integer range classic asp Figure 2.1
Output of Listing 2.1.1 When viewed through a browser.

Adding Elements to a 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 states of United of the Using the "Add method" (Lin Es 9 through 13). The Add method is takes one parameter, the element to Add to the array, and which needs to is type Object. This Object instance are 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 was 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 a ArrayList at once? The ArrayList class provides the AddRange method to does just this. AddRange expects a single parameter that supports ICollection interface. A wide number of. NET Framework Classes-such as the Array, ArrayList, DataView, DataSetView, and others-support this inter Face. On line at Listing 2.1.1, we use the AddRange method to add each element of the astates ArrayList to the "end of" the ATe Rritories ArrayList. (To add a range of elements starting at a specific index into ArrayList, use the Insertrange method.) On lines and, we add two strings to the end of the Aterritories ArrayList.

Because ArrayLists are ordered sequentially there, might want to "times" when we are particular to add the element to a position. The Insert method is 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 th e new element, which needs to is type Object. In line we add a new string to the start of the Aterritories ArrayList. Note this if we had simply used the Add method, "District of Columbia" would have the been to the ' end of added. Using Insert, however, we can specify exactly where in the ArrayList this new element should reside.

Removing Elements from ArrayList
The ArrayList class also provides a number of methods for removing elements. We can remove a specific element from a ArrayList with the Remove method. On line, we remove the String "Wyoming" from the Aterritories ArrayList. (If you are attempt to remove a element that is does not exist, a ArgumentException exception would be thrown.) Remove allows you-take out a particular element from a ArrayList; RemoveAt, used on line, 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 in a time. We can remove a chunk of elements in one fell swoop by using the RemoveRange method. This is expects two Parameters:an index to start in and a count of total elements to remove. In line we remove the "two elements in Aterritories" with the Statement:aTerritories.RemoveRange (0, 2). Finally, to remove the contents of a ArrayList, use the "Clear Method" (refer to Line Listing 2.1.1).

Referencing ArrayList Elements
Note This in our code example, we used two different techniques to iterate through of our contents. Because an ArrayList stores items sequentially, we can iterate through a ArrayList by looping to its lowest bound GH its upper bound and referencing each element by its integral index. The following code snippet is taken from lines through-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 We loop at 0 because all collections are indexed starting at 0. We can reference an ArrayList element with:aarraylistinstance (index), as "We Do", in Listing 2.1.1.

We can also step through the elements of any of the collection types we'll be looking to in this chapter using a For each ... Next Loop with (or a foreach loop with C #). A Simple example of this approach can is seen in the following code snippet from lines 52:

Dim S as String
For each s in aterritories
Lblfewerterritories.text = Lblfewerterritories.text & _
S & "<br>"
This is useful the to stepping through all to 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 a ArrayList, it would make sense to reference it in the aarraylistinstance (i NDEX) format. If, however, you are looking for a particular element into the ArrayList, you can use the IndexOf 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 is set to-1.) Two other forms of IndexOf can is used to specify a range for which to search for the. For more information in those methods, refer to the. NET Framework SDK documentation.

Working with the Hashtable Class
The type of collection most developers are used to working and is the hash table collection. Whereas the ArrayList indexes each element numerically, a hash table indexes each element by a alphanumeric key. The Collection data type in Visual Basic is a hash table; The Scripting.Dictionary object, used commonly in classic ASP pages, are 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 this ordering of elements in the collection are irrespective of th E 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 to ordered alphabetically by the value of the their keys to use the SortedList C Lass, which is discussed into 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 in the positions. 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 and whereas the clear method removes all elements from a Hashtable. Examples of both of these methods can is 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)
: ' Now, display a list of employees and their salaries
15:lblsalary.text = "<i>there are" & Htsalaries.count & _
: "Employees...</i><br>"
18:dim S as String
19:for each s in Htsalaries.keys
20:lblsalary.text &= S & "-" & Htsalaries (s) & "<br>"
: ' Is billg an Employee? If So, FIRE him!
24:if Htsalaries.containskey ("Billg") Then
25:htsalaries.remove ("Billg")
26:end If
: ' 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
Panax Notoginseng: </script>
: <body>
Salary information:</b><br>, <b>employee
: <asp:label id= "lblsalary" runat= "Server"/>
: <p>
A: <b>remaining Employees after Round one of firings:</b><br>
<asp:datagrid runat= "Server" id= "Dgemployees"
47:autogeneratecolumns= "True" showheader= "False"
48:cellspacing= "1" cellpadding= "4"/>
: </body>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.