The usage of foreach traversal in C#

The usage of foreach traversal in C# The
foreach loop is used to list all the elements in the collection. The expression in the foreach statement consists of two items separated by the keyword in. The item on the right of in is the name of the collection, and the item on the left of in is the name of the variable, used to store each element in the collection.

The running process of the loop is as follows: each time it loops, a new element value is taken from the set. Put it in a read-only variable. If the entire expression in the parentheses returns true, the statement in the foreach block can be executed. Once all the elements in the collection have been accessed, and the value of the entire expression is false, the control flow is transferred to
the execution statement after the foreach block .

The foreach statement is often used with an array. The following example will read the value of the array through the foreach statement and display it.

The attributes of the array: the capacity of the Array.Length array

Using this attribute, we can obtain the allowed storage capacity value of the array object, that is, the length of the array and the number of elements. This is easier to understand. The array has other attributes, such as the dimension of the array. The usage of the attribute is relatively simple. Learn one, the other formats are basically the same, we will not give examples here.

When the array has more dimensions and capacity, C# provides a foreach statement to read all elements in a collection/array. We call this function traversal. The grammar is written as follows:

Traverse the array: foreach (type objName in collection/Array)

This statement will check the stored variable values ​​in the array one by one, and take them out one by one. The type is the data type of the array object you want to read that will be stored in the objName variable, and objName defines a type type The variable name represents each element obtained from the collection and array (collection/Array), and collection/Array is the array object to be accessed. In this way, just write a foreach to traverse all the arrays of dimensions except the jagged array.

Note : The data type type of objName must be the same as or larger than the type of the collection/Array object.

Below we give an example of using foreach and for to traverse the rule array, which involves the method of obtaining the dimension of an array, and compares the advantages of foreach in one-time traversal of the rule array.

int[,,] a = new int[2, 2, 2] {
    
     {
    
    {
    
     1, 2 }, {
    
     3,4}},{
    
    {
    
     5, 6 }, {
    
     7,8}} };// 定义一个2行2列2纵深的3维数组a
for (int i = 0; i < a.GetLength (0) ;i++ )   //用Array.GetLength(n)得到数组[0,1,,,n]上的维数的元素数,0代表行,1列,n代表此数组是n+1维
{
    
    
    for (int j = 0; j < a.GetLength(1); j++)
    {
    
    
        for (int z = 0; z < a.GetLength(2);z++ )//2代表得到纵深上的元素数,如果数组有n维就得写n个for循环
        {
    
    
            Console.WriteLine(a[i,j,z]);
        }
    }
}

Use foreach loop to traverse a array at once

int[,,] a = new int[2, 2, 2] {
    
     {
    
    {
    
     1, 2 }, {
    
     3,4}},{
    
    {
    
     5, 6 }, {
    
     7,8}} };//定义一个2行2列2纵深的3维数组a
foreach(int i in a)
{
    
    
    Console .WriteLine (i);
}

The results of the execution of these two codes are the same. There is one element per line, a total of 8 lines, and the elements are 1 2 3 4 5 6 7 8

Let's make another example below, which is an example of accessing array elements using for and foreach loops. First, prompt the user to enter the number of students, and then use the number of students as the number of elements in the array names for storing student names. The for loop will output the prompt of "input student's name" starting from bit 0 according to the index i of the array, and store the name of the student entered by the user in the names array according to its index in the array, names[i], the maximum number of for loops The value (that is, the maximum value of the index) is obtained through the array property. Length, we said that the relationship between the capacity and the index is index=Array.Length-1, this question is the maximum value of i

It must be noted that with foreach, you can only get the elements in the array one by one, and you cannot use this statement to change the elements stored in the array.
Insert picture description here

using System;
class Program
{
    
    
    static void Main()
    {
    
    
        int count;
        Console.WriteLine("输入要登记的学生数");
        count = int.Parse(Console.ReadLine());
        string[]names = new string[count];
        for (int i = 0; i < names.Length; i++)
        {
    
    
            Console.WriteLine("请输入第{0}个学生的姓名", i + 1);
            names[i] = Console.ReadLine();
        }
        Console.WriteLine("已登记的学生如下");
        foreach (string name in names)
        {
    
    
            Console.WriteLine("{0}", name);
        }
        Console.ReadKey();
    }
}

Guess you like

Origin blog.csdn.net/weixin_43244265/article/details/106268458