How to: use Foreach in C# | Simon Deshaies

by Simon Deshaies 4/16/2008 9:41:55 PM

Understanding foreach was one of the toughest learning experience I had to go trough when learning C#. Foreach is use to iterate trough an Array 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 foreach statement 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 a DataSet 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 MySqlConnection class here as MySql.

MySqlConnection MySql = new MySqlConnection();

MySql.CreateConn();

SqlDataAdapter MyAdapter = new SqlDataAdapter("SELECT [UserName],[UserAge],[UserID] FROM [MyDatabase].[dbo].[Users] ORDER BY [UserID]", MySql.Connection);
DataTable MyDataTable = new DataTable();
MyAdapter.Fill(MyDataTable);

foreach (DataRow row in MyDataTable.Rows)
    Response.Write(Convert.ToString(row[2]) + " " + Convert.ToString(row[0]) + " " + Convert.ToString(row[1]) + "<br />");

MyAdapter.Dispose();
MyDataTable.Dispose();
MySql.CloseConn();
You Get:
exemple3 

Now the possibility are limitless...

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

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

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET | C# | How to:

Related posts

Comments

10/22/2008 1:13:21 AM

Great, it resolved a lot of stuff!

Jean-François McDuff ca

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

1/7/2009 9:47:23 AM

Powered by BlogEngine.NET 1.3.1.0
Theme by Mads Kristensen

www.aubergedeslegendes.com

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, CSS, ASP.NET, AJAX, C#, SQL.
Microsoft Windows Server 2000 to 2008, SQL Server, MySQL, IIS, DNS.


E-mail me Send mail

Calendar

<<  January 2009  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Pages

    Recent comments

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2009

    Sign in