📜  C#|在数组中使用foreach循环

📅  最后修改于: 2021-05-29 16:28:49             🧑  作者: Mango

C#语言提供了几种读取项目集合的技术。其中之一是foreach循环。 foreach循环提供了一种简单,干净的方法来遍历集合或项目数组的元素。我们必须知道的一件事是,在使用foreach循环之前,我们必须在程序中声明数组或集合。因为foreach循环只能迭代以前声明的任何数组或任何集合。我们不能像for循环那样使用foreach循环来打印数字或字符的序列,请参见下文:

for(i = 0; i <= 10; i++)
// we cannot use foreach loop in this way to print 1 to 10
// to print 1 to 10 using foreach loop we need to declare 
// an array or a collection of size 10 and a variable that 
// can hold 1 to 10 integer

foreach循环的语法:

foreach (Data_Type variable_name in Collection_or_array_Object_name)
 {
   //body of foreach loop
 }
// here "in" is a keyword

在这里, Data_Type是变量的数据类型,而variable_name是将迭代循环条件的变量(例如,for(int i = 0; i <10; i ++),这里i等效于variable_name)。 foreach循环使用的in关键字对iterable-item(此处为数组或集合)进行迭代。 in关键字在每次迭代时从iterable-item或数组或集合选择一个项目,并将其存储在变量(此处为variable_name)中。

示例1:下面是使用数组的“ for”和“ foreach”循环的实现

// C# program to show the use of
// "for" loop and "foreach" loop
using System;
  
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // initialize the array
        char[] arr = {'G', 'e', 'e', 'k', 's', 
                        'f', 'o', 'r', 'G', 'e', 
                                 'e', 'k', 's'};
          
  
        Console.Write("Array printing using for loop = ");
  
        // simple "for" loop
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write(arr[i]);
        }
  
        Console.WriteLine();
  
        Console.Write("Array printing using foreach loop = ");
  
        // "foreach" loop
        // "ch" is the variable
        // of type "char"
        // "arr" is the array 
        // which is going to iterates
        foreach(char ch in arr)
        {
            Console.Write(ch);
        }
    }
}
输出:
Array printing using for loop = GeeksforGeeks
Array printing using foreach loop = GeeksforGeeks

示例2:使用“ foreach”循环遍历数组

// C# program to traverse an 
// array using "foreach" loop
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        char[] s = {'1', '4', '3', '1',
                    '4', '3', '1', '4',
                                  '3'};
        int m = 0, n = 0, p = 0;
  
        // here variable "g" is "char" type
        //'g' iterates through array "s"
        // and search for the numbers 
        // according to below conditions
        foreach(char g in s)
        {
            if (g == '1')
                m++;
            else if (g == '4')
                n++;
            else
                p++;
        }
        Console.WriteLine("Number of '1' = {0}", m);
        Console.WriteLine("Number of '4' = {0}", n);
        Console.WriteLine("Number of '3' = {0}", p);
    }
}
输出:
Number of '1' = 3
Number of '4' = 3
Number of '3' = 3

注意:在foreach循环范围内的任何地方,我们都可以使用break关键字退出循环,也可以使用continue关键字进入循环中的下一个迭代。

示例:在foreach循环中使用“ continue”和“ break”关键字

// C# program to demonstrate the use 
// of continue and break statement
// in foreach loop
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // initialize the array
        int[] arr = {1, 3, 7, 5, 8,
                      6, 4, 2, 12};
  
        Console.WriteLine("Using continue:");
          
        foreach(int i in arr)
        {
            if (i == 7)
                continue;
            // here the control skips the next
            // line if the "i" value is 7
  
            // this line executed because 
            // of the "if" condition
            Console.Write(i + " ");
  
        }
  
        Console.WriteLine();
        Console.WriteLine("Using break:");
          
        foreach(int i in arr)
        {
              
            if(i == 7)
            // here if i become 7 then it will 
            // skip all the further looping 
            // statements
                break;
            Console.Write(i +" ");
        }
    }
}

输出:

Using continue:
1 3 5 8 6 4 2 12 
Using break:
1 3