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

相關文章
相關標籤/搜索