C # Supplements's foreach Iteration statement

Source: Internet
Author: User

The C # language provides a quick way to iterate over a for statement and also facilitates a more consistent collection class, which is the foreach statement.

The foreach statement is defined in the following format:

foreach (type variable in collection)

{

Sub-statement;

}

Each time the inline statement is executed, the loop variable takes one of the elements in the collection in turn, where the loop variable is a read-only local variable, such as attempting to change its value will cause a compilation error.

The foreach statement is used to enumerate all the elements in the collection, and the expressions in the foreach statement consist of two items separated by the keyword in. The item on the right is the collection name, and the item on the left is the variable name that holds each element in the collection.

The advantage of a foreach statement is that the statement is concise and efficient.

Use an example that iterates over an array element to illustrate:

First use the foreach statement to output the elements in the array:

<span style= "FONT-SIZE:18PX;" >            int[,] ints =new int[2,3]{{1,2,3},{4,5,6}};            foreach (int temp in ints)            {                Console.WriteLine (temp);             }            Console.ReadLine ();</span>

then use the For statement to output the elements in the array:

           <span style= "FONT-SIZE:18PX;" >     int[,] ints =new int[2,3]{{1,2,3},{4,5,6}};            for (int i = 0; i < INTs. GetLength (0); i++)            {for                (int j = 0; J < INTs. GetLength (1); J + +)                {                    Console.WriteLine (ints[i,j]);}            }            Console.ReadLine ();</span>

The result of both code execution is the same as one element per line, a total of 6 rows, and the elements are 1 2 3 4 5 6 respectively.

In a one-dimensional array, the simplicity and efficiency of the foreach statement cannot be demonstrated, but it is more obvious and convenient in a two-dimensional array or even a multidimensional array, so a foreach statement is advocated in the C # language using a looping statement.

Advantages of the foreach statement two: avoid unnecessary factors

        use a foreach statement in the C # language without regard to the array start index, Many people may go from other languages to c# 1 For example vb delphi language, so in c# In the end use the 0 start or use 1 start, so foreach

Three advantages of the foreach statement: The foreach statement automatically Completing type Conversions

this embodiment may not show any effect through the example above , but for ArrayList such a data set, this operation is more prominent.

The type conversion operation is first implemented with the foreach statement: Using the ArrayList class is the first to introduce a using System.Collections;

<span style= "FONT-SIZE:18PX;" >            int[] a=new int[3]{1,2,3};            ArrayList arrint = new ArrayList ();            Arrint. AddRange (a);            foreach (int temp in arrint)            {                Console.WriteLine (temp);            }            Console.ReadLine ();</span>

again, use the FOR statement: Explicit casts are required

<span style= "FONT-SIZE:18PX;" >            int[] a=new int[3]{1,2,3};            ArrayList arrint = new ArrayList ();            Arrint. AddRange (a);            for (int i = 0; i < Arrint. count;i++)            {                int n = (int) arrint[i];                Console.WriteLine (n);            }            Console.ReadLine ();</span>

the results of the two program outputs are: one element per line, and three to three.
The foreach statement is more concise for the string class:

<span style= "font-size:18px;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks;  Namespace @foreach {class Program {static void Main (string[] args) {string str = ' This is            An example of a foreach "; foreach (char i in str) {if (char. Iswhitespace (i)) {Console.WriteLine (i);//When I is a space, output and wrap} El SE {console.write (i);//When I is not a space just output}} console.read        Line (); }}}</span> 

The result of the output is: one word per line, respectively, this, was, an, example, of, A, foreach.
for the understanding of the foreach statement, it is now known that more, with deeper learning, perhaps there will be a better understanding of it.




C # Supplements's foreach Iteration statement

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.