.

How to: use Foreach in C#

by Simon Deshaies 16. April 2008 15:41

Understanding foreach was one of the toughest learning experience I had to go trough when learning C#. Foreach is use to iterate trough anArray or a Collection. When searching the web for examples of how to actually use it I never found enough. I decided to show a couple of example that I would of wish I had found at the time.

msdn says: The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreachstatement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects. The statement takes the following form:

foreach (type identifier in expression) statement
http://msdn2.microsoft.com/en-us/library/ttw7t8t6(vs.71).aspx

In my first example I first built an Array of 5 object, then for each object contained in the array I write a line on the web page.

string[] myArray = new string[5];

myArray[0] = "One";
myArray[1] = "Two";
myArray[2] = "Three";
myArray[3] = "Four";
myArray[4] = "Five";

foreach (object arrayObject in myArray)
{
    Response.Write(arrayObject + "<br />");
}

You Get:

exemple1

The parameters, object is the type of repeated item I'm interested in. The arrayObject is the identifier (variable I declare to represent the array object), in in this context means the exact same thing then in the English language. myArray is the Array itself. I know I’m repeating the same information again, but since we are talking about iteration...

In my second example I will be doing the same thing with different key words and using a for statement to built my array.

string[] secondExampleArray = new string[10];

for (int i = 0; i < 10; i++)
    secondExampleArray[i] = "Number " + i;

foreach (object sEA in secondExampleArray)
    Response.Write(sEA + "<br />");

You Get:

exemple2

This second example is more straight forward. I really wanted to show you an alternative way to write it. Remember that the first index is away* [0].

In this third example I'll show you how to use if with a collection. I will use a DataTable and iterate trough the rows. You could also use aDataSet that contains one or more DataTable. Here is where it gets interesting, unlike the object the DataRow contains an array of data. it's easy to get confused and search hours how to access the data. The quick solution is if you initialized our DataRow as row, you would get the first table column object of the array by row[0]. I'm using the SqlConnection class here as connection.

using (SqlConnection connection = new SqlConnection())
{
    SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT [UserName],[UserAge],[UserID] FROM [MyDatabase].[dbo].[Users] ORDER BY [UserID]"
        , connection.Connection);
    DataTable dataTable = new DataTable();
    adapter.Fill(dataTable);
    
    foreach (DataRow row in dataTable.Rows)
        Response.Write(Convert.ToString(row[2]) 
            + " " + Convert.ToString(row[0]) 
            + " " + Convert.ToString(row[1]) 
            + "<br />");
}

You Get:
exemple3 

Now the possibility are limitless...

You may download the sample web site it contains all the code, the SqlConnection class and the database. Have Fun!

Please leave comments about the appreciation of my articles it means allot to me.

Comments

10/21/2008 7:13:21 PM #

Jean-François McDuff

Great, it resolved a lot of stuff!

Jean-François McDuff Canada

Powered by BlogEngine.NET
Theme by Mads Kristensen and Simon Deshaies

About the author

Simon Deshaies

Name of authorI do web development, I focus on your business processes by dramatically increasing your visibility. I develop strong Internet and Web applications. My main objective is to support your performance by optimizing your presence on the Web and to advise you on the best web technology to fit your needs.

Linked in profile

Specialties:
.NET development, Internet and Web applications.
HTML, XHTML, XML, XSL, CSS, ASP.NET, AJAX, C#, SQL.
Microsoft Windows Server 2000 to 2008, SQL Server 2000 to 2008, MySQL, IIS, DNS.

BlogRoll

Download OPML file OPML