Home > Net >  C # foreach usage
C # foreach usage

Time:10-09

Foreach loop is used to enumerate all elements in the collection, can use the foreach iteration array or a collection of objects, cheng & gt;

?? Every cycle, from the collection took out a new element values, to read-only variables, if the entire expression in parentheses the return value is true, foreach block can execute the statement in, once all the elements in the collection should be access to the entire value of the expression is false, the control process is transferred into the foreach block behind the execution of the statement,


Class Program {static void Main (string [] args) {int [] array=new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9}; {foreach (int I in array) Console. WriteLine (I); }}} it implements the traversal of array elements, traverse before need to specify the type of the element

12345678910111213

//result 1 2 3 4 5 6 7 8 9

12345678910


Class Program {static void Main (string [] args) {string test="Hello, world!" ; The foreach (char I test) in {Console. WriteLine (I); }}}

1234567891011

/result/H e l l o w o r l d.

12345678910111213

To replace the I type char with int

//results 44 119 111 114 108 72 101 108 108 111 100 33 output is the result of the characters of the ASCII value of the data types of implicit conversion here

1234567891011121314


Variable name used to store the collection of each element is a class ArrayList or List, it can make the foreach to traverse the


Class Program {static void Main (string [] args) {int count; Console. WriteLine (" to enter the registration number of students "); Count=int. Parse (Console. ReadLine ()); String [] names=new string (count);//declare a store name string array, its length is equal to the number of students for providing (int I=0; I & lt; Names. Length; I++)//accept name {Console. WriteLine (" please enter the names of the students into the first {0} ", I + 1); Names [I]=Console. ReadLine (); } the Console. WriteLine (" registered students as follows "); The foreach (string name names) in//display name {Console. WriteLine (" {0} ", name); } the Console. ReadKey (); }}

123456789101112131415161718192021


The foreach loop is read-only and cannot be traversed modify data is only in the foreach loop, and is a a cycle

CodePudding user response:

Good

CodePudding user response:

CodePudding user response:

Did not understand what are you going to do,

CodePudding user response:

Foreach within each traverse a will determine whether a logo, this logo is removed or add data to record collection, if remove complains, different for loop, it is for internal use element array index to operate, even if to remove the item will not go wrong,

CodePudding user response:

CodePudding user response:

# 4 positive solution, foreach has an internal version matching version of identity,
  • Related