2025-04-27 07:49:33 -04:00

250 lines
13 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html dir=ltr><head><title>Working with Collections</title>
<SCRIPT LANGUAGE="JavaScript">
<!--
TempString = navigator.appVersion
if (navigator.appName == "Microsoft Internet Explorer"){
// Check to see if browser is Microsoft
if (TempString.indexOf ("4.") >= 0){
// Check to see if it is IE 4
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/coua.css">');
}
else {
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/cocss.css">');
}
}
else if (navigator.appName == "Netscape") {
// Check to see if browser is Netscape
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/coua.css">');
}
else
document.writeln('<link rel="stylesheet" type="text/css" href="/iishelp/common/cocss.css">');
//-->
</script>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Window_OnLoad()
Dim frmContents
On Error Resume Next
If Not Parent Is Nothing Then
Set frmContents = Parent.Contents
If Not frmContents Is Nothing Then
frmContents.Window.TOCSynch_Click
End If
End If
End Sub
//--></SCRIPT>
<META NAME="DESCRIPTION" CONTENT="Explains how to use the built-in object collections, including iterating through a collection. Includes VBScript and JScript code samples."><META HTTP-EQUIV="Content-Type" content="text/html; charset=Windows-1252">
<META HTTP-EQUIV="PICS-Label" CONTENT='(PICS-1.1 "<http://www.rsac.org/ratingsv01.html>" l comment "RSACi North America Server" by "inet@microsoft.com <mailto:inet@microsoft.com>" r (n 0 s 0 v 0 l 0))'>
<META NAME="MS.LOCALE" CONTENT="EN-US">
<META NAME="MS-IT-LOC" Content="Internet Information Services">
</head>
<body bgcolor="#FFFFFF" text="#000000"><font face="Verdana,Arial,Helvetica">
<h1><a name="usingcollections">Working with Collections</a></h1>
<p>Most of the ASP built-in objects provide collections. <em>Collections</em> are data structures similar to arrays that store strings, numbers, objects and other values. Unlike arrays, collections expand and contract automatically as items are retrieved or stored. The position of an item will also move as the collection is modified. You can access an item in a collection by its unique string key, by its index (position) in the collection, or by iterating through all the items in the collection.</p>
<h2><a name="H2_37766951">Accessing an Item by Name or Index</a></h2>
<p>You can access a specific item in a collection by referencing its unique string key, or name. For example, the <strong>Contents</strong> collection holds any variables stored in the <strong>Session</strong> object. It can also hold any objects instantiated by calling <strong>Server.CreateObject</strong>. Suppose you have stored the following user information in the <strong>Session</strong> object:</p>
<pre>&lt;%
Session.Contents("FirstName") = "Meng"
Session.Contents("LastName") = "Phua"
Session.Contents("Age") = 29
%&gt;</pre>
<p>You can access an item by using the string key you associated with the item when you stored it in the collection. For example, the following expression returns the string "Meng":</p>
<pre>&lt;%= Session.Contents("FirstName") %&gt;</pre>
<p>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 position of the <strong>Session</strong> object and returns "Phua":</p>
<pre>&lt;%= Session.Contents(2) %&gt;</pre>
<p>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&#146;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.</p>
<p>You can also use a shorthand notation to access items by name. 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 (although doing so may affect performance):</p>
<pre>&lt;%= Session("FirstName") %&gt;</pre>
<p>Eliminating the collection name is generally safe when you are accessing items stored in the <strong>Application</strong> or <strong>Session</strong> object. For the <strong>Request</strong> object, however, it is safer to specify the collection name because the collections could easily contain items with duplicate names.</p>
<h2><a name="H2_37768485">Iterating through a Collection</a></h2>
<p>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 <strong>For...Each</strong> statement to access the items you stored in the <strong>Session</strong> object:</p>
<pre>&lt;%
'Declare a counter variable.
Dim strItem
'For each item in the collection, display its value.
For Each strItem In Session.Contents
Response.Write Session.Contents(strItem) & "&lt;BR&gt;"
Next
%&gt;</pre>
<p>You can also iterate through a collection by using the VBScript <strong>For...Next</strong> statement. For example, to list the three items stored in <strong>Session</strong> by the previous example, use the following statements:</p>
<pre>&lt;%
'Declare a counter variable.
Dim intItem
'Repeat the loop until the value of counter is equal to 3.
For intItem = 1 To 3
Response.Write Session.Contents(intItem) & "&lt;BR&gt;"
Next
%&gt;</pre>
<p>Because you do not usually know how many items are stored in a collection, ASP supports the <strong>Count</strong> property for a collection, which returns the number of items in the collection. You use the <strong>Count</strong> property to specify the end value of the counter.</p>
<pre>&lt;%
'Declare a counter variable.
Dim lngItem, lngCount
lngCount = Session.Contents.Count
'Repeat this loop until the counter equals the number of items
'in the collection.
For lngItem = 1 To lngCount
Response.Write Session.Contents(lngItem) & "&lt;BR&gt;"
Next
%&gt;</pre>
<p>In JScript, you use the <strong>for</strong> statement to loop through a collection. For greater efficiency when using the <strong>Count</strong> property with a JScript <strong>for</strong> statement, you should assign the value of <strong>Count</strong> 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 <strong>Count</strong> each time through the loop. The following example demonstrates this technique:</p>
<pre>&lt;%
var intItem, intNumItems;
intNumItems = Session.Contents.Count;
for (intItem = 1; intItem &lt;= intNumItems; intItem++)
{
Response.Write(Session.Contents(intItem) + "&lt;BR&gt;")
}
%&gt;</pre>
<p>Microsoft JScript supports an <strong>Enumerator</strong> object that you can also use to iterate through an ASP collection. The <strong>atEnd</strong> method indicates whether there are any more items in the collection. The <strong>moveNext</strong> method moves to the next item in the collection.</p>
<pre>&lt;%
Session.Contents("Name") = "Suki White"
Session.Contents("Department") = "Hardware"
.
.
.
//Create an Enumerator object.
var mycollection = new Enumerator(Session.Contents);
//Iterate through the collection and display each item.
while (!mycollection.atEnd())
{
var x = myCollection.item();
Response.Write(Session.Contents(x) + "&lt;BR&gt;");
myCollection.moveNext();
}
%&gt;</pre>
<h2><a name="H2_37771913">Iterating through a Collection with Subkeys</a></h2>
<p>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 <strong>Cookies</strong> collection of the <strong>Request</strong> and <strong>Response</strong> objects can thus hold multiple values in a single item. These subitems, or subkeys, can be accessed individually. Subkeys are supported only by the <strong>Request.Cookies</strong> and <strong>Response.Cookies</strong> collections. <strong>Request.Cookies</strong> supports only read operations; <strong>Response.Cookies</strong> supports only write operations.</P>
<P>The following creates a regular cookie and a cookie with a subkeys:</P>
<PRE>&lt;%
'Send a cookie to the browser.
Response.Cookies("Fruit") = "Pineapple"
'Send a cookie with subkeys to browser.
Response.Cookies("Mammals")("Elephant") = "African"
Response.Cookies("Mammals")("Dolphin") = "Bottlenosed"
%&gt;</PRE>
<P>The cookie text in the HTTP response sent to the browser would appear as the following:</P>
<PRE>HTTP_COOKIE= Mammals=ELEPHANT=African&DOLPHIN=Bottlenosed; Fruit=Pineapple;</PRE>
<p>You can also enumerate all the cookies in the <strong>Request.Cookies</strong> collection and all the subkeys in a cookie. However, iterating through subkeys on a cookie that does not have subkeys will not produce an item. You can avoid this situation by first checking to see whether a cookie has subkeys by using the <strong>HasKeys</strong> attribute of the <STRONG>Cookies</STRONG> collection. This technique is demonstrated in the following example.</p>
<pre>&lt;%
'Declare counter variables.
Dim Cookie, Subkey
'Display the entire cookie collection.
For Each Cookie In Request.Cookies
Response.Write Cookie
If Request.Cookies(Cookie).HasKeys Then
Response.Write "&lt;BR&gt;"
'Display the subkeys.
For Each Subkey In Request.Cookies(Cookie)
Response.Write " -&gt" & Subkey & " = " & Request.Cookies(Cookie)(Subkey) & "&lt;BR&gt;"
Next
Else
Response.Write " = " & Request.Cookies(Cookie) & "&lt;BR&gt;"
End If
Next
%&gt;</pre>
<P>This script would return the following results:</P>
<PRE>Mammals
-&gt;ELEPHANT = African
-&gt;DOLPHIN = Bottlenosed
Fruit = Pineapple</PRE>
<H2><a name="H2_321118501">The Case of the Key Name</a></H2>
<p>The <STRONG>Cookies</STRONG>, <STRONG>Request</STRONG>, <STRONG>Response</STRONG>, and <STRONG>ClientCertificate</STRONG> collections can reference the same, unique string key name. For example, the following statements reference the same key name, <EM>User</EM>, but return different values for each collection:</p>
<pre>strUserID = Request.Cookies("User")
strUserName = Request.QueryString("User")</pre>
<P>The case of the key name is set by the first collection to assign a value to the key. Examine the following script:</P>
<pre>&lt;%
'Retrieve a value from QueryString collection using the UserID key.
strUser = Request.QueryString("UserID")
'Send a cookie to the browser, but reference the key, UserId, which has a different spelling.
Response.Cookies("UserId")= "1111-2222"
Response.Cookies("UserId").Expires="December 31, 2000"
%&gt;
</pre>
<P>Although it may appear that key name <EM>UserId</EM> was assigned to the cookie, in actuality, the key name <EM>UserID</EM> (which is capitalized differently) was assigned to the cookie. The <STRONG>QueryString</STRONG> collection was first to define the case of this key.
<P>Because references to collection values are independent of the case of the key name, this behavior will not affect your scripts unless your application uses case sensitive processing of key names.</P>
<h2><a name="H3_37773518">Iterating through a Collection of Objects</a></h2>
<p>The <strong>Session</strong> and <strong>Application</strong> collections can hold either scalar variables or object instances. The <strong>Contents</strong> collection holds both scalar variables and object instances created by calling <strong>Server.CreateObject</strong>. The <strong>StaticObjects</strong> collection holds objects created by using the HTML &lt;OBJECT&gt; tag within the scope of the <STRONG>Session</STRONG> object. For more information about instantiating objects in this manner, see <A HREF="iiwaobu.htm">Setting Object Scope</A>.</p>
<p>When you iterate through a collection that contains objects, you can either access the object's Session or Application state information 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 <strong>StaticObjects</strong> collection to retrieve object properties:</p>
<pre>&lt;%
For Each Object in Session.StaticObjects
Response.Write Object & ": " & Session.StaticObjects(Object)
Next
%&gt;</pre>
<h2><a name="H3_37774582">What&#146;s Different About ASP Collections?</a></h2>
<p>Although the ASP collections described in this topic are similar to the Visual Basic <strong>Collection</strong> object, there are some differences. The ASP collections support the <strong>Count</strong> property and the <strong>Item</strong>, <STRONG>Remove</STRONG>, and <STRONG>RemoveAll</STRONG> methods. They do not support the <strong>Add</strong> method.</p>
<hr class="iis" size="1">
<p align="center"><em><a href="/iishelp/common/colegal.htm">&copy; 1997-2001 Microsoft Corporation. All rights reserved.</a></em></p>
</font>
</body>
</html>