獲取 C# 中 foreach 迴圈當前迭代的索引
    
    
            Minahil Noor
    2023年10月12日
    
    Csharp
    Csharp Loop
    
 
在 C# 中,我們主要有兩個迴圈,for 迴圈和 foreach 迴圈。foreach 迴圈被認為是最好的,因為它適用於所有型別的操作。即使對於那些我們不需要索引 index 值的物件。
在某些情況下,我們需要使用 foreach 迴圈,但是我們還必須獲取 index 索引值。為了解決這個問題,在 C# 中,我們有不同的方法來獲取 foreach 迴圈當前迭代的 index,例如,Select() 和索引變數方法。
C# 使用 Select() 方法獲取 foreach 迴圈當前迭代的 index
Select() 方法是 LINQ 方法。LINQ 是 C# 的一部分,用於訪問不同的資料庫和資料來源。Select() 方法選擇 foreach 迴圈迭代的值和索引 index。
使用此方法的正確語法如下:
Select((Value, Index) => new { Value, Index });
示例程式碼:
using System;
using System.Linq;
using System.Collections.Generic;
public class IndexOfIteration {
  public static void Main() {
    // Creating integer List
    List<int> Numbers = new List<int>() { 1, 2, 3, 4, 8, 10 };
    // Visiting each value of List using foreach loop
    foreach (var New in Numbers.Select((value, index) => new { value, index })) {
      Console.WriteLine("The Index of Iteration is: {0}", New.index);
    }
  }
}
輸出:
The Index of Iteration is: 0
The Index of Iteration is: 1
The Index of Iteration is: 2
The Index of Iteration is: 3
The Index of Iteration is: 4
The Index of Iteration is: 5
C# 使用索引變數方法獲取 foreach 迴圈當前迭代的 index
這是查詢 foreach 迴圈迭代的索引 index 的傳統且最簡單的方法。在此方法中,我們使用變數並將其初始化為零,然後在每次迭代中增加該值。
示例程式碼:
using System;
using System.Collections.Generic;
public class IndexOfIteration {
  public static void Main() {
    // Creating an integer List
    List<int> Numbers = new List<int>() { 1, 2, 3, 4, 8, 10 };
    int index = 0;
    // Visiting each value of List using foreach loop
    foreach (var Number in Numbers) {
      Console.WriteLine("The Index of Iteration is {0}", index);
      index++;
    }
  }
}
輸出:
The Index of Iteration is: 0
The Index of Iteration is: 1
The Index of Iteration is: 2
The Index of Iteration is: 3
The Index of Iteration is: 4
The Index of Iteration is: 5
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe