//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
      Basic Language Constructs
      Themes & Skins (web)
      Tips & Techniques
      XML Serialization
   Classic ASP 1.0
   Databases
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
asp.net2.aspfaq.com

ASP FAQ Tutorials :: ASP.NET 2.0 :: Basic Language Constructs :: for vs. foreach


Using for and foreach with arrays, arraylists and other collections

Overview

Most people are familiar with working with lists like arrays, array lists, hashtables and other collections.  A common action with these types of objects is to loop through them and there have always been a variety of ways of doing this with operators like for, whiledo/until etc.  Many people are not familiar with the foreach construct though.

Standard For

In a standard for loop, you would do something like this.  Let's say that you have a standard string array with 6 names in it as follows:

CSharp

    // An array of names...
    string[] namesArray = new string[] { "John", "Jack", "James", 
                                         "Mary", "Mindy", "Mandy" };

VB

    ' An array of names...
    String() namesArray = New String() { "John", "Jack", "James", 
                                         "Mary", "Mindy", "Mandy" 
                                         }


Now, let's say that we wanted to print these names onto a web page using Response.Write.  To do this using a regular for loop, the code would look something like this:

CSharp

    // Print string array
    for (int i = 0; i < namesArray.Length; i++)
    {
        Response.Write(namesArray[i] + "...<br>");
    }

VB

    ' Print string array
    Dim i As Integer
    For  i = 0 To  namesArray.Length- 1  Step  i + 1
        Response.Write(namesArray(i) + "...<br>")
    Next

Now lets say that we wanted to print these names from an array list.  The following code would do this.  Notice that in the first for loop, we had to check for namesArray.Length, while this time, it has to use nameArrayList.Count.

CSharp

    ArrayList namesArrayList = new ArrayList(namesArray);
    for (int i = 0; i < namesArrayList.Count; i++)
    {
        Response.Write(namesArray[i] + "...<br>");
    }

VB

    Dim namesArrayList As ArrayList =  New ArrayList(namesArray) 
    Dim i As Integer
    For  i = 0 To  namesArrayList.Count- 1  Step  i + 1
        Response.Write(namesArray(i) + "...<br>")
    Next


This is just one of many problems with using a for loop.  You always have to "know" the count/length.  You have to know if it's a 0 or 1 based array, etc.   In this case we're working with strings, so it's pretty straightforward, but things also get more complicated when working with complex object types since we have to explicitly convert each object before we can use it.

Now let's look at this same functionality using the foreach construct.

CSharp

    // Print string array
    foreach (string name in namesArray)
    {
        Response.Write(name + "...<br>");
    }

    // Print array list
    ArrayList namesArrayList = new ArrayList(namesArray);
    foreach (string name in namesArrayList)
    {
        Response.Write(name + "...<br>");
    }

VB

    ' Print string array
    Dim name As String
    For Each name In namesArray
        Response.Write(name + "...<br>")
    Next
 
    ' Print array list
    Dim namesArrayList As ArrayList =  New ArrayList(namesArray) 
    Dim name As String
    For Each name In namesArrayList
        Response.Write(name + "...<br>")
    Next


There are a few things that should be pointed out about this code as compared with the for syntax.
  1. You don't have to know the bounds/dimentions of the array
  2. It automatically gives you an instance (of the right type) of whatever is collected by the array (a string in this case).
  3. The syntax (and therefore the resulting code) is just so much cleaner
  4. This same syntax will work whether you're iterating over an array, ArrayListHashtable or any other type of collection.

The complete code for this sample application is listed below.

default.aspx.cs/vb

CSharp

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        PrintNamesWithFor();
        PrintNamesWithForeach();
    }

    // An array of names...
    string[] namesArray = new string[] { "John", "Jack", "James", 
                                        "Mary", "Mindy", "Mandy" };
 
    // Print each name on it's own line
    private void PrintNamesWithFor()
    {
        // Print string array
        for (int i = 0; i < namesArray.Length; i++)
        {
            Response.Write(namesArray[i] + "...<br>");
        }
 
        // Print array list
        ArrayList namesArrayList = new ArrayList(namesArray);
        for (int i = 0; i < namesArrayList.Count; i++)
        {
            Response.Write(namesArray[i] + "...<br>");
        }
    }
 
    private void PrintNamesWithForeach()
    {
        // Print string array
        foreach (string name in namesArray)
        {
            Response.Write(name + "...<br>");
        }
 
        // Print array list
        ArrayList namesArrayList = new ArrayList(namesArray);
        foreach (string name in namesArrayList)
        {
            Response.Write(name + "...<br>");
        }
    }
}

VB

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Collections
 
Public partial Class _Default
     Inherits System.Web.UI.Page
    Protected  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        PrintNamesWithFor()
        PrintNamesWithForeach()
    End Sub
 
    ' An array of names...
    String() namesArray = New String() { "John", "Jack", "James", 
                                        "Mary", "Mindy", "Mandy" 
                                        }

 
    ' Print each name on it's own line
    Private  Sub PrintNamesWithFor()
        ' Print string array
        Dim i As Integer
        For  i = 0 To  namesArray.Length- 1  Step  i + 1
            Response.Write(namesArray(i) + "...<br>")
        Next
 
        ' Print array list
        Dim namesArrayList As ArrayList =  New ArrayList(namesArray) 
        Dim i As Integer
        For  i = 0 To  namesArrayList.Count- 1  Step  i + 1
            Response.Write(namesArray(i) + "...<br>")
        Next
    End Sub
 
    Private  Sub PrintNamesWithForeach()
        ' Print string array
        Dim name As String
        For Each name In namesArray
            Response.Write(name + "...<br>")
        Next
 
        ' Print array list
        Dim namesArrayList As ArrayList =  New ArrayList(namesArray) 
        Dim name As String
        For Each name In namesArrayList
            Response.Write(name + "...<br>")
        Next
    End Sub
End Class


default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

'----------------------------------------------------------------
' Converted from C# to VB .NET using CSharpToVBConverter(1.2).
' Developed by: Kamal Patel (http://www.KamalPatel.net)
'----------------------------------------------------------------

Related Articles

Using Hashtables

 

 


Created: 6/7/2006 | Last Updated: 6/7/2006 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (615)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...