C# 中的 foreach 迴圈


foreach 迴圈對實現 System.Collections.IEnumerable 或 System.Collections.Generic.IEnumerable<T> 介面的型別例項中的每個元素執行一個語句或一組語句。

示例

讓我們看一個 foreach 迴圈的示例 −

 線上演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      LinkedList<int> linkedList = new LinkedList<int>();
      linkedList.AddLast(25);
      linkedList.AddLast(50);
      linkedList.AddLast(100);
      linkedList.AddLast(200);
      linkedList.AddLast(400);
      linkedList.AddLast(500);
      linkedList.AddLast(550);
      linkedList.AddLast(600);
      linkedList.AddLast(800);
      linkedList.AddLast(1200);
      Console.WriteLine("Count of nodes = " + linkedList.Count);
      foreach(int val in linkedList){
         Console.WriteLine(val);
      }
      Console.WriteLine("Does the LinkedList has node 800? "+linkedList.Contains(800));
   }
}

輸出

這將產生以下輸出 −

Count of nodes = 10
25
50
100
200
400
500
550
600
800
1200
Does the LinkedList has node 800? True

更新於: 11-12-2019

409 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.