Easy Tutorial
❮ Linux Common Command 2 Javascript Find Min Max ❯

The use of foreach loop in C# for iteration

Category Programming Techniques

The foreach loop is used to enumerate all elements in a collection. The expression in the foreach statement consists of two items separated by the keyword 'in'. The item on the right side of 'in' is the collection name, and the item on the left side is the variable name, which is used to store each element of the collection.

The operation process of this loop is as follows: Each time the loop iterates, a new element value is taken from the collection and placed in a read-only variable. If the entire expression in the parentheses returns a true value, the statements in the foreach block can be executed. Once all the elements in the collection have been accessed, the value of the entire expression becomes false, and the control flow transfers to the execution statement following the foreach block.

The foreach statement is often used with arrays. The following example will demonstrate how to read the values of an array and display them using the foreach statement.

Array Property: Array.Length - the capacity of the array

Using this property, we can obtain the capacity value allowed by the array object, which is the length or the number of elements in the array. This is relatively easy to understand. Arrays also have other properties, such as the number of dimensions of the array. The usage of properties is relatively simple; once you learn one, the format of the others is basically consistent. We won't provide examples here.

When the dimensions and capacity of the array are numerous, C# provides the foreach statement specifically for reading all elements in a collection/array. We refer to this functionality as iteration. The syntax is written as follows:

Iterating through an array: foreach (type objName in collection/Array)

This statement will check each variable value stored in the array one by one and retrieve them. The 'type' is the data type that the array object you want to read will be stored in the variable 'objName', and 'objName' is the name of a variable of type 'type', representing each element obtained from the collection and array (collection/Array). This method allows you to iterate through all dimensions of an array except for jagged arrays with just one foreach.

Note: The data type of 'objName', 'type', must be the same as or larger than the type of the collection/Array object.

Below is an example of iterating through a regular array using both foreach and for loops, involving a method to obtain the dimensions of an array and comparing the advantages of using foreach for one-time iteration through a regular array.

Example

int[,,] a = new int[2, 2, 2] { {{ 1, 2 }, { 3,4}},{{ 5, 6 }, { 7,8}} };// Define a 3D array 'a' with 2 rows, 2 columns, and 2 depths
for (int i = 0; i < a.GetLength(0); i++) // Use Array.GetLength(n) to get the number of elements in the nth dimension of the array, where 0 represents rows, 1 represents columns, and n represents that the array is n+1 dimensional
{
    for (int j = 0; j < a.GetLength(1); j++)
    {
        for (int z = 0; z < a.GetLength(2); z++) // 2 represents obtaining the number of elements in the depth; if the array has n dimensions, you need to write n for loops
        {
            Console.WriteLine(a[i,j,z]);
        }
    }
}

Using a foreach loop to iterate through the 'a' array in one go

Example

int[,,] a = new int[2, 2, 2] { {{ 1, 2 }, { 3,4}},{{ 5, 6 }, { 7,8}} };// Define a 3D array 'a' with 2 rows, 2 columns, and 2 depths
foreach(int i in a)
{
    Console.WriteLine(i);
}

Both of these code executions result in the same output, with each line containing one element, for a total of 8 lines, with the elements being 1, 2, 3, 4, 5, 6, 7, and 8.

Let's look at another example, which involves using for and foreach loops to store and retrieve array elements. First, prompt the user to enter the number of students, then use the number of students as the number of elements in the 'names' array for storing student names. Use a for loop to cycle through the array index 'i' starting from position 0,

❮ Linux Common Command 2 Javascript Find Min Max ❯