For Each and The Collection

For Each and The Collection

In C#, the foreach loop is a useful construct for iterating through elements in a collection. It simplifies the code required to traverse a collection by abstracting the iteration process.

Here’s the basic syntax for using foreach loop in C#:

foreach (var item in collection)


    // code to execute for each item


Here, collection is the name of the collection you want to iterate through, and item is a variable that will hold each item in the collection as it’s processed. The var keyword is used to declare the type of the item variable implicitly.

For example, consider the following code that uses a foreach loop to iterate through an array of integers:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (var number in numbers)




In this example, each item in the numbers array is processed one by one in the loop, and its value is printed to the console.

The foreach loop can also be used to iterate through other types of collections, such as lists, dictionaries, and sets. The syntax for using foreach loop remains the same, but you’ll need to specify the appropriate collection type as the collection parameter.

The For Each loop that you see in action inside the Button1_Click routine. Here’s the line of code from Step 4 that begins the sequence:

foreach (ListItem chbx in CBL.Items)

It helps to parse the line starting at the far right to put the code into English. It says, “Here’s a collection of items. You know that each of these items is a ListItem type. Let the variable chbx (at least for now) represent the first ListItem in this collection. Now move to the next line of code.”

With chbx representing the first item within the collection, you can examine the item’s Selected property. If the CheckBox has been checked, the Selected property’s value is True and you therefore proceed inside the If statement to find the following line:

strSel = strSel + chbx.Text + “<br/>”;

Again, it helps to look to the right side of the code to describe what’s happening. Here, you peer into the value of the Text property for the CheckBox (forexample, “Crosswords”). You take that text, attach an HTML carriage return and add this onto whatever is in the strSel variable. (On the first loop, nothing is in strSel.)

After exiting the If statement, you run into the loop. let’s do the same thing with the next one.” The sequence repeats until the ForEach…Next combination announces.

Apply for ASP.NET Certification Now!!

Back to Tutorial

Get industry recognized certification – Contact us