Using Collections

Most of the ASP built-in objects support collections. A collection is a place to store strings, numbers, objects and other values. A collection is is similar to an array except that it expands and contracts automatically as items are stored in or retrieved from the collection. Unlike an array, the position of an item will move as the collection is modified. You can access an item in a collection by its name, by its index (position) in the collection, or by iterating through all the items in the collection.

Accessing an Item by Name or Index

You can access a specific item in a collection by using its name. For example, the Contents collection holds any variables stored in the Session object. It also holds any objects created by calling Server.CreateObject. Suppose you have stored the following user information in the Session object:

<%
Session.Contents("FirstName") = "Sam"
Session.Contents("LastName") = "Woo"
Session.Contents("Age") = 29
%>

You can access an item by using the name you associated with the item when you stored it in the collection. For example, the following expression returns the string "Sam":

<%= Session.Contents("FirstName") %>

You could also access an item by using the index, or number, associated with an item. For example, the following expression retrieves the information stored in the second slot of the Session object and returns "Woo":

<%= Session.Contents(2) %>

ASP collections are numbered starting with 1. The index associated with an item might change as items are added to or removed from the collection. You should not depend on an item’s index remaining the same. Indexed access is generally used to iterate through a collection, as described in the following topics, or to access an item in a read-only collection.

You can access items by name using a shorthand notation. ASP searches the collections associated with an object in a particular order. If an item with a particular name appears only once in an object's collections, you can eliminate the collection name:

<%= Session("FirstName") %>

Eliminating the collection name is generally safe when you are accessing items stored in the Application or Session object. For the Request object, however, it is safer to specify the collection name because the collections could easily contain items with duplicated names.

Iterating through a Collection

You can iterate through all the items in a collection to see what is stored in the collection or to modify the items. You must supply the collection name when you iterate through a collection. For example, you can use the VBScript For...Each statement to access the items you stored in the Session object:

<% 
'Declare a counter variable.
Dim Item 

'For each item in the collection, display its value.
For Each Item in Session.Contents 
  Response.Write Session.Contents(Item) & "<BR>"
Next
%>

You can also iterate through a collection by using the VBScript For...Next statement. For example, to list the three items stored in Session by the previous example, use the following statements:

<% 
'Declare a counter variable.
Dim Item

'Repeat the loop until the value of counter is equal to 3.
For Item = 1 to 3
  Response.Write Session.Contents(Item) & "<BR>"
Next
%>

Because you do not usually know how many items are stored in a collection, ASP supports the Count property for a collection, which returns the number of items in the collection. You use the Count property to specify the end value of the counter.

<% 
'Declare a counter variable.
Dim Item

'Repeat this loop until the counter equals the number of items
'in the collection.
For Item = 1 to Session.Contents.Count
   Response.Write Session.Contents(Item) & "<BR>"
Next
%>

In JScript, you use the for statement to loop through a collection. For greater efficiency when using the Count property with a JScript for statement, you should assign the value of Count to a local variable and use that variable to set the end value of the counter. That way, the script engine does not have to look up the value of Count each time through the loop. The following example demonstrates this technique:

<% 
var item, numitems;
numitems = Session.Contents.Count;
for (item = 1; item <= numitems; item++) {
  Response.Write(Session.Contents(item) + "<BR>")
}
%>

Version 3.0 of Microsoft JScript introduces a new Enumerator object that you can also use to iterate through an ASP collection. The atEnd method indicates whether there are any more items in the collection. The moveNext method moves to the next item in the collection.

<%
// Create an Enumerator object
var mycoll = new Enumerator(Session.Contents);

//Iterate through the collection and display each item
while (!mycoll.atEnd()) {
  var x  = mycoll.item();
  Response.Write(Session.Contents(x) + "<BR>");
  mycoll.moveNext();
}
%>

Iterating through a Collection with Subkeys

Scripts might embed several related values in a single cookie to reduce the number of cookies passed between the browser and the Web server. The Cookies collection of the Request and Response objects can thus hold multiple values in a single item. These subitems, or subkeys, can be accessed individually. Subkeys are supported only by the Request.Cookies and Response.Cookies collections. Request.Cookies supports only read operations; Response.Cookies supports only write operations.

You can enumerate all the cookies in the Request.Cookie collection and all the subkeys in a cookie. However, iterating through subkeys on a cookie that does not have subkeys will not produce any output. You can avoid this situation by first checking to see whether a cookie has subkeys by using the .HasKeys syntax. This technique is demonstrated in the following example.

<% 
'Declare counter variables
Dim Cookie, Subkey

'Display the entire cookie collection.
For Each Cookie in Request.Cookies
  Response.Write Cookie & "<BR>"
    If Request.Cookies(Cookie).HasKeys Then
      'Display the subkeys
      For Each Subkey in Request.Cookies(Cookie)
	Response.Write Subkey & "=" & Request.Cookies(Cookie)(Subkey) & "<BR>"
      Next
    Else
      Response.Write "No subkeys in this cookie <BR>"
    End If
Next    
%>

Iterating through a Collection of Objects

The Session and Application collections can hold either scalar variables or object instances. The Contents collection holds both scalar variables and object instances created by calling Server.CreateObject. The StaticObjects collection holds objects created by using the HTML <OBJECT> element in the Global.asa file.

When you iterate through a collection that contains objects, you can either access the object’s identifier or access the object’s methods or properties. For example, suppose your application uses several objects to create a user account, and each object has an initialization method. You could iterate through the StaticObjects collection to call each initialization method:

<%
For Each Object in Session.StaticObjects
  Session.StaticObjects(Object).InitializeUser
Next
%>

What’s Different About ASP Collections?

Although the ASP collections described in this topic are similar to the Visual Basic Collection object, there are some differences. The ASP collections support the Count property and the Item method. They do not support the Add and Remove methods.