C#学习经常使用方法(3000)---Foreach ,in

foreach 语句对实现 System.Collections.IEnumerableSystem.Collections.Generic.IEnumerable<T> 接口的数组或对象集合中的每一个元素重复一组嵌入式语句。  foreach 语句用于循环访问集合,以获取您须要的信息,但不能用于在源集合中添加或移除项,不然可能产生不可预知的反作用。  若是须要在源集合中添加或移除项,请使用 for 循环。数组

嵌入语句为数组或集合中的每一个元素继续执行。  当为集合中的全部元素完成迭代后,控制传递给 foreach 块以后的下一个语句。ide

能够在 foreach 块的任何点使用 break 关键字跳出循环,或使用 continue 关键字进入循环的下一轮迭代。oop

foreach 循环还能够经过 gotoreturnthrow 语句退出。spa


示例code

如下代码显示了三个示例:orm

  • 显示整数数组内容的典型的 foreach 循环对象

  • 执行相同操做的 for 循环接口

  • 维护数组中的元素数计数的 foreach 循环element

class ForEachTest
{    static void Main(string[] args)
    {        
    int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };        
    foreach (int element in fibarray)
        {
            System.Console.WriteLine(element);
        }
        System.Console.WriteLine();       
         // Compare the previous loop to a similar for loop.
        for (int i = 0; i < fibarray.Length; i++)
        {
            System.Console.WriteLine(fibarray[i]);
        }
        System.Console.WriteLine();        
        // You can maintain a count of the elements in the collection.
        int count = 0;       
         foreach (int element in fibarray)
        {
            count += 1;
            System.Console.WriteLine("Element #{0}: {1}", count, element);
        }
        System.Console.WriteLine("Number of elements in the array: {0}", count);
    }    // Output:
    // 0
    // 1
    // 1
    // 2
    // 3
    // 5
    // 8
    // 13

    // 0
    // 1
    // 1
    // 2
    // 3
    // 5
    // 8
    // 13

    // Element #1: 0
    // Element #2: 1
    // Element #3: 1
    // Element #4: 2
    // Element #5: 3
    // Element #6: 5
    // Element #7: 8
    // Element #8: 13
    // Number of elements in the array: 8}


备注:转载自https://msdn.microsoft.com/zh-cn/library/ttw7t8t6.aspx
get

************************************************************************

C# 还提供 foreach 语句。  该语句提供一种简单、明了的方法来循环访问数组或任何可枚举集合的元素。  foreach 语句按数组或集合类型的枚举器返回的顺序处理元素,该顺序一般是从第 0 个元素到最后一个元素。  例如,如下代码建立一个名为 numbers 的数组,并使用 foreach 语句循环访问该数组:

  int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };        
  foreach (int i in numbers)
        {
            System.Console.Write("{0} ", i);
        }       
         // Output: 4 5 6 1 2 3 -2 -1 0

借助多维数组,你能够使用相同的方法来循环访问元素,例如:

  int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };        
  // Or use the short form:        
  // int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

        foreach (int i in numbers2D)
        {
            System.Console.Write("{0} ", i);
        }        // Output: 9 99 3 33 5 55

但对于多维数组,使用嵌套的 for 循环能够更好地控制数组元素。


备注转载自:https://msdn.microsoft.com/zh-cn/library/2h3zzhdw.aspx

相关文章
相关标签/搜索