跳過到頁腳內容
.NET幫助

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);
}
$vbLabelText   $csharpLabel

在這個例子中,number 表示每次迭代期間集合中的元素。 循環會自動遍歷數組中的所有元素。 但是,目前沒有內建方法來存取目前元素的索引。

在 foreach 迴圈中處理索引

雖然 C# 沒有直接在 foreach 迴圈中提供索引,但有幾種方法可以解決這個問題。 讓我們詳細討論一下這些方法。

方法一:使用單獨的變數

取得目前元素索引的最簡單方法之一是使用外部索引變數。 你需要在循環內部手動遞增它:

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

在這段程式碼中,索引變數在循環開始之前初始化,然後在循環內的每次迭代中遞增。 雖然這種方法可行,但需要手動維護索引,這並不總是理想的。

方法二:使用 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 循環可以遍歷這些對象,並直接存取索引和值。

方法三:使用自訂迭代器

您可以使用 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

C# foreach 循環帶索引(開發者使用方法):圖 1 - 索引輸出

這種方法允許你透過將索引變數用作數組或列表的下標來直接存取索引和當前元素。

.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 迴圈允許你直接遍歷鍵值對。 這是在每次迭代中同時存取鍵和值的常見用例:

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 給出當前鍵,而 kvp.Value 給出當前值。

使用IronPDF和 C# foreach 迴圈和索引

C# foreach 迴圈(附索引)(開發者使用方法):圖 2 - IronPDF

IronPDF是一個 PDF 庫,用於處理從 HTML 生成 PDF以及在 C# 中執行其他與 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 迴圈(附索引)(開發者使用方法):圖 3 - PDF 輸出

結論

C# foreach 迴圈(附索引)(開發者使用方法):圖 4 - 授權

在 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 迴圈可以通過訪問每個鍵值對來迭代字典。這允許開發者在迭代過程中直接處理鍵和值。

在 C# 開發中使用 PDF 庫有什麼好處?

PDF 庫使開發者可以從 HTML 生成 PDF 並在 C# 中執行各種 PDF 操作。它們通常提供免費試用版以探索功能,並提供可購買的許可證。

如何在 C# 中使用 while 迴圈進行索引迭代?

while 迴圈可以與索引變量一起使用,以便在 C# 中遍歷集合,利用索引用作下標來訪問索引和當前元素。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me