This article mainly introduces the knowledge about the For loop and the Foreach loop in C #, which has a good reference value. Let's take a look at the little series.
The For loop and the Foreach loop can actually be a dependency, that is, the Foreach loop can be converted into a for loop, but the for loop does not necessarily translate into a foreach loop.
Here's a brief look at two loops:
1.for Cycle
Code format:
for (expression 1; loop condition; expression 2)
{
Loop body
}
Code meaning:
First run the expression 1;
Then determine whether the condition is true, if true, then execute the loop body, after execution, then run the expression 2;
Then judge the cycle conditions ... The loop will end until the loop condition is false.
Precautions:
Expression 1: Can be any code that is bound to be executed and executed only once;
Expression 2: Can be any code that executes after the loop body executes.
2.foreach Cycle
Code format:
foreach (data type variable in array or collection)
{
Loop body
}
Code meaning:
From an array or collection, take each item's data in turn, and then assign the data to the loop variable each time the data is fetched, and run the loop body once each assignment.
Precautions:
A foreach loop can only be used to iterate over arrays and collections;
The Foreach loop is also called a read-only loop, and the collection or array cannot be changed in the loop body;
The data type must be the same as the data type of each item in the array or collection.
But what are the differences and pros and cons of the Foreach loop and the For loop? Here's a brief summary:
foreach Loop For Loop
Can only be used for traversal, and may be used in any form of repetitive behavior;
The loop target cannot be changed, and any operation can be done in the loop body;
Fast traverse speed and high execution efficiency. Slow traversal and low execution efficiency.
Summary: If you need to traverse a collection or array, and the traversal is only required to read without changing, the Foreach loop is the most appropriate, and conversely, the other loops are selected as needed.