We know that if,else,for,while,switch, variables, etc. are fundamental to the process, and this article is about the difference between for and Foreach in. NET:
--The For loop primarily iterates through the data and filters the data that meets the criteria.
--The Foreach loop is primarily a one-time traversal of data.
Note: There are two kinds of circulation methods have good and bad, in different scenes adopt different circulation way, vary from person to person.
Here's a simple example to resolve the differences between the two loops:
The main operating environment is VS2010, with console as an example.
Example of a For loop
Defining a String array
string[] str = new string[]{"A1", "B2", "C3", "D4", "E5"};
Gets the number of array lengths
int length = Str.length;
Iterating through an array
for (int index=0;index<length;index++) {
Search for a string containing the keyword "3"
if (Str[index]. Contains ("3")) {
Console.WriteLine (Str[index]);
}
}
Example of a Foreach loop
Defining a String array
string[] str = new string[]{"A1", "B2", "C3", "D4", "E5"};
Iterating through an array
Foreach (var s in str) {
Console.WriteLine (s);
}
--Obviously the Foreach loop is more concise than the code for the For Loop . LINQ in NET3.5 , the code you write is more concise and interesting. NET beginner pays tribute to the little brother.
This article is from the "12067158" blog, please be sure to keep this source http://12077158.blog.51cto.com/12067158/1885645
Differences between. NET for and foreach