C# foreach與索引(對開發者如何理解的工作)
在C#中,foreach語句通常用於迭代遍曆像陣列、列表或其他可枚舉型別的集合。然而,一個限制是foreach迴圈沒有提供內建的索引變數來追蹤當前的迭代。 開發者常常需要存取當前元素的索引。 下面,我們將探索實現該功能的各種方法和IronPDF程式庫。
foreach迴圈的基本概念
foreach迴圈旨在簡化對陣列、列表、字典和其他實現IEnumerable的型別的遍歷。 這裡有一個基本範例,說明如何使用foreach語句來遍歷整數資料型別的陣列:
int[] numbers = { 10, 20, 30, 40 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
int[] numbers = { 10, 20, 30, 40 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Dim numbers() As Integer = { 10, 20, 30, 40 }
For Each number As Integer In numbers
Console.WriteLine(number)
Next number
在此範例中,number表示集合在每次迭代中的元素。 該迴圈會自動遍歷陣列中的所有元素。 然而,沒有內建的方法來存取當前元素的索引。
在foreach迴圈中處理索引
儘管C#不直接在foreach迴圈中提供索引,但有幾種技術可以解決這個問題。 讓我們詳細討論這些方法。
方法1:使用單獨的變數
獲取當前元素索引的最簡單方法之一是使用一個外部索引變數。 您需要在迴圈內手動增加它:
int[] numbers = { 10, 20, 30, 40 };
int numberIndex = 0;
foreach (int number in numbers)
{
Console.WriteLine($"Index: {numberIndex}, Value: {number}");
numberIndex++;
}
int[] numbers = { 10, 20, 30, 40 };
int numberIndex = 0;
foreach (int number in numbers)
{
Console.WriteLine($"Index: {numberIndex}, Value: {number}");
numberIndex++;
}
Dim numbers() As Integer = { 10, 20, 30, 40 }
Dim numberIndex As Integer = 0
For Each number As Integer In numbers
Console.WriteLine($"Index: {numberIndex}, Value: {number}")
numberIndex += 1
Next number
在此程式碼中,索引變數是在迴圈開始前初始化的,然後在每次迭代中在迴圈內增加。 雖然該方法有效,但需要手動維護索引,這並不總是理想的。
方法2:使用LINQ的Select方法
LINQ的Select方法可以用於將集合的每個元素投影成一個新形式,包括其索引。 這裡有一個範例:
int[] numbers = { 10, 20, 30, 40 };
foreach (var item in numbers.Select((value, index) => new { value, index }))
{
Console.WriteLine($"Index: {item.index}, Value: {item.value}");
}
int[] numbers = { 10, 20, 30, 40 };
foreach (var item in numbers.Select((value, index) => new { value, index }))
{
Console.WriteLine($"Index: {item.index}, Value: {item.value}");
}
Dim numbers() As Integer = { 10, 20, 30, 40 }
For Each item In numbers.Select(Function(value, index) New With {
Key value,
Key index
})
Console.WriteLine($"Index: {item.index}, Value: {item.value}")
Next item
在此範例中,Select建立了一個匿名物件,其中包含當前元素的值及其索引。 然後,foreach迴圈可以迭代這些物件,直接存取索引和值。
方法3:使用自定義迭代器
您可以使用yield return關鍵字實現自定義迭代器擴展方法,以生成一個同時產生當前元素及其索引的方法。 這有點更高級,但提供了靈活的解決方案。
public static IEnumerable<(int index, T value)> WithIndex<t>(this IEnumerable<t> source)
{
int index = 0;
foreach (T value in source)
{
yield return (index, value);
index++;
}
}
public static IEnumerable<(int index, T value)> WithIndex<t>(this IEnumerable<t> source)
{
int index = 0;
foreach (T value in source)
{
yield return (index, value);
index++;
}
}
Imports System.Collections.Generic
Public Module Extensions
<System.Runtime.CompilerServices.Extension>
Public Iterator Function WithIndex(Of T)(source As IEnumerable(Of T)) As IEnumerable(Of (index As Integer, value As T))
Dim index As Integer = 0
For Each value As T In source
Yield (index, value)
index += 1
Next
End Function
End Module
現在,您可以使用此擴展方法與您的集合一起使用:
int[] numbers = { 10, 20, 30, 40 };
foreach (var (index, value) in numbers.WithIndex())
{
Console.WriteLine($"Index: {index}, Value: {value}");
}
int[] numbers = { 10, 20, 30, 40 };
foreach (var (index, value) in numbers.WithIndex())
{
Console.WriteLine($"Index: {index}, Value: {value}");
}
Dim numbers() As Integer = { 10, 20, 30, 40 }
foreach var(index, value) In numbers.WithIndex()
Console.WriteLine($"Index: {index}, Value: {value}")
Next
這種方法通過將手動索引管理抽象到一個可重用的方法中,建立了一個更優雅的foreach帶索引問題的解決方案。
使用while迴圈存取索引
如果您正在處理像陣列或列表之類的集合,您可以使用一個索引變數配合while迴圈來存取索引和當前元素:
int[] numbers = { 10, 20, 30, 40 };
int index = 0;
while (index < numbers.Length)
{
Console.WriteLine($"Index: {index}, Value: {numbers[index]}");
index++;
}
int[] numbers = { 10, 20, 30, 40 };
int index = 0;
while (index < numbers.Length)
{
Console.WriteLine($"Index: {index}, Value: {numbers[index]}");
index++;
}
Dim numbers() As Integer = { 10, 20, 30, 40 }
Dim index As Integer = 0
Do While index < numbers.Length
Console.WriteLine($"Index: {index}, Value: {numbers(index)}")
index += 1
Loop

這種方法允許您通過使用索引變數作為陣列或列表的下標直接存取索引和當前元素。
.NET中的自定義集合和迭代器
如果您正在處理定制的集合,您可以實現自己的迭代器以支持索引存取。 通過實現IEnumerable接口和使用yield return語句,您可以建立迭代器來返回元素及其索引。
這裡有一個建立自定義集合並實現IEnumerable的範例:
public class CustomCollection<t> : IEnumerable<t>
{
private T[] _items;
public CustomCollection(T[] items)
{
_items = items;
}
public IEnumerator<t> GetEnumerator()
{
for (int i = 0; i < _items.Length; i++)
{
yield return _items[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class CustomCollection<t> : IEnumerable<t>
{
private T[] _items;
public CustomCollection(T[] items)
{
_items = items;
}
public IEnumerator<t> GetEnumerator()
{
for (int i = 0; i < _items.Length; i++)
{
yield return _items[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Imports System.Collections
Imports System.Collections.Generic
Public Class CustomCollection(Of T)
Implements IEnumerable(Of T)
Private _items As T()
Public Sub New(items As T())
_items = items
End Sub
Public Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
For i As Integer = 0 To _items.Length - 1
Yield _items(i)
Next
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
End Class
然後您可以在foreach迴圈中使用此自定義集合:
var customCollection = new CustomCollection<int>(new int[] { 10, 20, 30, 40 });
foreach (int number in customCollection)
{
Console.WriteLine(number);
}
var customCollection = new CustomCollection<int>(new int[] { 10, 20, 30, 40 });
foreach (int number in customCollection)
{
Console.WriteLine(number);
}
Dim customCollection As New CustomCollection(Of Integer)(New Integer() { 10, 20, 30, 40 })
For Each number As Integer In customCollection
Console.WriteLine(number)
Next number
通過實現yield return,您建立了一個迭代器,讓foreach迴圈能夠像使用其他.NET集合一樣使用您的自定義集合。
使用字典和鍵值對來進行迭代
處理字典時,foreach迴圈允許您直接遍歷鍵值對。 這是在每次迭代中存取鍵和值的一個常用例:
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Apple" },
{ 2, "Banana" },
{ 3, "Cherry" }
};
foreach (var kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Apple" },
{ 2, "Banana" },
{ 3, "Cherry" }
};
foreach (var kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
Dim dict As New Dictionary(Of Integer, String) From {
{1, "Apple"},
{2, "Banana"},
{3, "Cherry"}
}
For Each kvp In dict
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}")
Next kvp
在此範例中,kvp.Value提供您當前的值。
在C# foreach迴圈和索引中使用IronPDF

IronPDF是用於處理從HTML生成PDF和其他PDF相關任務的PDF程式庫。 它也與最新的.NET Framework相容。 在使用IronPDF生成PDF時,您可能需要迭代資料集合並動態將內容插入到PDF文件中。將foreach迴圈與索引處理結合使用,可以根據集合中當前項目的索引來管理定位、編號或自定義邏輯。 這裡是一個使用IronPDF建立PDF的實用範例,將集合中的每個項目連同其索引插入文件中。
using IronPdf;
class Program
{
static void Main(string[] args)
{
// Create a new PDF document renderer
var pdf = new ChromePdfRenderer();
// Sample data array
string[] items = { "First Item", "Second Item", "Third Item" };
// Initialize the HTML content with foreach loop and index
string htmlContent = "<html><body>";
int index = 0;
foreach (var item in items)
{
htmlContent += $"<h2>Item {index + 1}: {item}</h2>";
index++;
}
htmlContent += "</body></html>";
// Render the HTML to PDF
var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
// Save the PDF document
pdfDocument.SaveAs("output.pdf");
// Notify completion
Console.WriteLine("PDF created successfully with indexed items.");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
// Create a new PDF document renderer
var pdf = new ChromePdfRenderer();
// Sample data array
string[] items = { "First Item", "Second Item", "Third Item" };
// Initialize the HTML content with foreach loop and index
string htmlContent = "<html><body>";
int index = 0;
foreach (var item in items)
{
htmlContent += $"<h2>Item {index + 1}: {item}</h2>";
index++;
}
htmlContent += "</body></html>";
// Render the HTML to PDF
var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
// Save the PDF document
pdfDocument.SaveAs("output.pdf");
// Notify completion
Console.WriteLine("PDF created successfully with indexed items.");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Create a new PDF document renderer
Dim pdf = New ChromePdfRenderer()
' Sample data array
Dim items() As String = { "First Item", "Second Item", "Third Item" }
' Initialize the HTML content with foreach loop and index
Dim htmlContent As String = "<html><body>"
Dim index As Integer = 0
For Each item In items
htmlContent &= $"<h2>Item {index + 1}: {item}</h2>"
index += 1
Next item
htmlContent &= "</body></html>"
' Render the HTML to PDF
Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
' Save the PDF document
pdfDocument.SaveAs("output.pdf")
' Notify completion
Console.WriteLine("PDF created successfully with indexed items.")
End Sub
End Class
這裡是輸出的PDF文件:

結論

在C#中,雖然foreach迴圈是一種遍歷集合的方便方式,但它缺乏對索引的原生支持。 然而,有幾種方法可以克服這一限制。 無論您是使用簡單的索引變數、LINQ的Select方法,還是自定義的迭代器,您都可以在迭代過程中獲得當前或下一個元素的索引。 了解這些技術可以幫助您更有效地使用foreach迴圈,特別是在需要知道每個元素的索引時。
使用IronPDF,您無需立即做出承諾。 我們提供一個免費試用,讓您深入探索該軟體的功能。 如果您滿意所見,許可從$999開始。
常見問題
如何在C#的foreach迴圈中跟蹤元素的索引?
要在C#的foreach迴圈中跟蹤索引,您可以手動增加一個獨立的索引變數,使用LINQ的Select方法來投影帶有索引的元素,或者建立一個自訂迭代器來同時輸出元素及其索引。
什麼是LINQ Select方法,它如何幫助進行索引?
LINQ的Select方法可以將集合中的每個元素轉換成包含元素索引的新形式。此種投影允許您在foreach迴圈中同時存取元素及其索引。
如何在C#中建立一個自訂迭代器來進行索引?
在C#中可以使用yield return關鍵字來建立自訂迭代器。這允許您構建一個迭代集合的方法,並同時輸出當前元素及其索引,簡化了迴圈索引。
PDF程式庫能夠協助在C#中建立帶索引的內容嗎?
是的,一個像IronPDF的PDF程式庫可以與C#的foreach迴圈一起使用來遍歷資料集合,並將帶索引的內容插入到PDF中。此方法允許動態內容定位和精確索引。
您如何使用C#中的foreach迴圈遍歷字典?
在C#中,foreach迴圈可以通過存取每個鍵值對來迭代字典。這允許開發人員在迭代過程中直接處理鍵和值。
在C#開發中使用PDF程式庫有何好處?
PDF程式庫可讓開發者從HTML生成PDF並在C#中執行各種PDF操作。它們通常提供免費試用以探索功能,並提供可購買的授權。
while迴圈如何用於C#中的索引迭代?
while迴圈可以與索引變數一起使用以在C#中遍歷集合,通過利用索引作為下標來存取索引和當前元素。




