.NET HELP C# foreach with index (How It Works For Developers) Jacob Mellor 更新:2025年7月22日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在 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); } $vbLabelText $csharpLabel 在這個範例中,數字代表每次迭代時集合的元素。 循環會自動遍歷陣列中的所有元素。 然而,沒有內建的方式可以存取目前元素的索引。 在 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++; } $vbLabelText $csharpLabel 在此程式碼中,索引變數會在循環開始前初始化,然後在每次迭代時在循環內遞增。 雖然這種方法可行,但需要手動維護索引,這並不總是理想的做法。 方法 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}"); } $vbLabelText $csharpLabel 在這個範例中,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++; } } $vbLabelText $csharpLabel 現在,您可以將此延伸方法用於您的作品集: 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}"); } $vbLabelText $csharpLabel 此方法透過將手動索引管理抽象為可重複使用的方法,為有索引的 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++; } $vbLabelText $csharpLabel 透過使用索引變數作為陣列或清單的下標,此方法可讓您直接存取索引和目前的元素。 .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(); } } $vbLabelText $csharpLabel 然後您就可以在 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); } $vbLabelText $csharpLabel 透過實作 GetEnumerator 方法並使用 yield return,您可以建立一個迭代器,讓 foreach 環路可以像 .NET 中的其他集合一樣使用您的自訂集合。 使用詞典和迭代鍵-值對 在處理字典時,foreach 環路可讓您直接遍歷 key-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}"); } 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}"); } $vbLabelText $csharpLabel 在這個範例中,kvp.Key 會提供您目前的 key,而 kvp.Value 則會提供您目前的 value。 使用 IronPDF 與 C# foreach 環路和索引 IronPDF 是一個 PDF 函式庫,用來在 C# 中處理 PDF 從 HTML 產生以及其他 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."); } } $vbLabelText $csharpLabel 以下是輸出的 PDF 檔案: 結論 在 C# 中,foreach 環路雖然是迭代集合的方便方式,但卻缺乏對索引的原生支援。 然而,有幾種方法可以克服這個限制。 無論您是使用簡單的索引變數、LINQ 的 Select 方法,或是自訂的迭代器,您都可以在迭代過程中存取目前或下一個元素的索引。 了解這些技術可以幫助您更有效率地使用 foreach 循環,尤其是當您需要知道每個元素的索引時。 有了 IronPDF,您不必立即投入工作。 我們提供 免費試用,讓您深入探索軟體的功能。 如果您喜歡您所看到的,許可證的起價為 $799 。 常見問題解答 如何追蹤 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 環路可以透過存取每個 key-value 對來遍歷字典。這可讓開發人員在迭代過程中直接處理鍵和值。 在 C# 開發中使用 PDF 函式庫有什麼好處? PDF 函式庫可讓開發人員從 HTML 產生 PDF,並在 C# 中執行各種 PDF 操作。它們通常提供免費試用以探索功能,並可購買授權。 如何在 C# 中使用 while 環路進行索引迭代? 在 C# 中,可以使用 while 環路與索引變數來遍歷集合,利用索引作為下標,同時允許存取索引與目前的元素。 Jacob Mellor 立即與工程團隊聊天 首席技術長 Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。 相關文章 更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多 更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多 C# Indexers (How It Works For Developers)Socket io .NET (How It Works For De...
更新2025年12月11日 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 閱讀更多
更新2025年12月20日 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 閱讀更多
更新2025年12月20日 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 閱讀更多