Differences between. NET for and foreach

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.