跳至頁尾內容
.NET 幫助

C# For Each(開發者如何實現)

在本教程中,我們將介紹"C# foreach"循環,這是開發人員必不可少的工具。 foreach循環簡化了遍歷集合的過程,使用戶更容易對每個項目執行操作,而無需擔心底層細節。 我們將討論foreach的重要性、它的用例以及如何在 C# 程式碼中實現它。

foreach迴圈簡介

foreach迴圈是開發人員以簡潔易讀的方式遍歷集合的強大工具。 它簡化了程式碼,減少了出錯的幾率,因為無需手動管理集合項目的索引或計數。 就可讀性和簡潔性而言, foreach迴圈通常比傳統的for迴圈更受歡迎。

foreach的使用場景包括:

  • 對集合中的值進行求和 在收藏中尋找物品
  • 修改集合中的元素
  • 對集合中的每個元素執行操作

了解館藏

C# 中有不同類型的集合,用於在單一物件中儲存一組項目。 其中包括數組、列表、字典等等。 foreach迴圈是一個有用的工具,可以與任何實作了IEnumerableIEnumerable介面的集合一起使用。 IEnumerable介面.

一些常見的收藏類型包括:

  • 陣列:固定大小的元素集合,這些元素具有相同的資料類型。
  • 清單:具有相同資料類型的元素的動態集合。
  • 字典:鍵值對的集合,其中每個鍵都是唯一的。

System.Collections.Generic命名空間包含用於處理集合的各種類型。

在 C# 中實作foreach語句

現在我們已經對集合和foreach循環有了基本的了解,讓我們深入了解語法,看看它在 C# 中是如何運作的。

foreach迴圈的語法

foreach (variableType variableName in collection)
{
    // Code to execute for each item
}
foreach (variableType variableName in collection)
{
    // Code to execute for each item
}
$vbLabelText   $csharpLabel

這裡, variableType表示集合中項目的資料型別, variableName是迴圈中目前項目的名稱(迴圈變數), collection指的是你要遍歷的集合。

例子

讓我們考慮一個例子,假設我們有一個整數列表,我們想要找到列表中所有元素的總和。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a list of integers
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Initialize a variable to store the sum
        int sum = 0;

        // Iterate through the list using foreach loop
        foreach (int number in numbers)
        {
            sum += number;
        }

        // Print the sum
        Console.WriteLine("The sum of the elements is: " + sum);
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a list of integers
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Initialize a variable to store the sum
        int sum = 0;

        // Iterate through the list using foreach loop
        foreach (int number in numbers)
        {
            sum += number;
        }

        // Print the sum
        Console.WriteLine("The sum of the elements is: " + sum);
    }
}
$vbLabelText   $csharpLabel

輸出

循環執行時,會輸出以下結果。

The sum of the elements is: 15

在上面的例子中,我們先建立一個名為numbers的整數列表,並初始化一個變數sum來儲存元素的總和。 然後,我們使用foreach循環遍歷列表,並將每個元素的值加到總和中。 最後,我們將總和列印到控制台。 這種方法也可以應用於列印或以類似方式處理其他集合。

變體和最佳實踐

現在我們已經基本了解如何使用foreach循環,接下來讓我們討論一些變體和最佳實踐。

只讀迭代: foreach迴圈最適合只讀迭代,因為在迭代過程中修改集合可能會導致意外結果或執行時錯誤。 如果在迭代過程中需要修改集合,請考慮使用傳統的for迴圈或建立一個包含所需修改的新集合。

使用var關鍵字:與其明確指定集合中元素的資料類型,不如使用var關鍵字讓編譯器推斷資料類型。 這樣可以讓程式碼更簡潔,更容易維護。

例子:

foreach (var number in numbers)
{
    Console.WriteLine(number);
}
foreach (var number in numbers)
{
    Console.WriteLine(number);
}
$vbLabelText   $csharpLabel

遍歷字典:當使用foreach循環遍歷字典時,您需要使用KeyValuePair結構。 此結構表示字典中的鍵值對。

例子:

Dictionary<string, int> ageDictionary = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 25 },
    { "Charlie", 22 }
};

foreach (KeyValuePair<string, int> entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
}
Dictionary<string, int> ageDictionary = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 25 },
    { "Charlie", 22 }
};

foreach (KeyValuePair<string, int> entry in ageDictionary)
{
    Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
}
$vbLabelText   $csharpLabel

LINQ 和foreach LINQ(語言整合查詢)是 C# 中的一項強大功能,它允許您以更宣告式的方式查詢和操作資料。 您可以將 LINQ 與foreach循環結合使用,以創建更具表現力和效率的程式碼。

例子:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Use LINQ to filter out even numbers
        var evenNumbers = numbers.Where(n => n % 2 == 0);

        // Iterate through the even numbers using foreach loop
        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Use LINQ to filter out even numbers
        var evenNumbers = numbers.Where(n => n % 2 == 0);

        // Iterate through the even numbers using foreach loop
        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
$vbLabelText   $csharpLabel

在 C# foreach迴圈中新增 IronPDF 功能教學課程

在本節中,我們將透過介紹 IronPDF(一個用於在 C# 中處理 PDF 文件的流行庫)來擴展我們關於"C# foreach"循環的教程。 我們將示範如何結合 IronPDF 使用foreach循環來產生基於資料集合的 PDF 報告。

IronPDF簡介

IronPDF 是一個功能強大的 C# 庫,用於建立、編輯和提取 PDF 文件內容。 它提供了一個易於使用的 API 來處理 PDF 文檔,對於需要在應用程式中整合 PDF 功能的開發人員來說,這是一個絕佳的選擇。

IronPDF 的一些主要功能包括:

  • 從 HTML、URL 和圖像生成 PDF
  • 編輯現有PDF文檔 從PDF文件中提取文字和圖像
  • 新增註解、表單欄位和加密功能

安裝 IronPDF

要開始使用 IronPDF,您需要安裝 IronPDF NuGet 套件。 您可以按照 IronPDF 文件中的說明進行操作。

使用 IronPDF 和foreach產生 PDF 報告

在這個範例中,我們將使用 IronPDF 庫和foreach循環來建立一個包含產品清單(包括產品名稱和價格)的 PDF 報告。

首先,我們建立一個簡單的Product類別來表示產品:

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }
}
public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product(string name, decimal price)
    {
        Name = name;
        Price = price;
    }
}
$vbLabelText   $csharpLabel

接下來,我們建立一個Product清單來產生 PDF 報表:

List<Product> products = new List<Product>
{
    new Product("Product A", 29.99m),
    new Product("Product B", 49.99m),
    new Product("Product C", 19.99m),
};
List<Product> products = new List<Product>
{
    new Product("Product A", 29.99m),
    new Product("Product B", 49.99m),
    new Product("Product C", 19.99m),
};
$vbLabelText   $csharpLabel

現在,我們可以使用 IronPDF 和foreach循環來產生包含產品資訊的 PDF 報告:

using System;
using System.Collections.Generic;
using IronPdf;

class Program
{
    static void Main()
    {
        // Create a list of products
        List<Product> products = new List<Product>
        {
            new Product("Product A", 29.99m),
            new Product("Product B", 49.99m),
            new Product("Product C", 19.99m),
        };

        // Initialize an HTML string to store the report content
        string htmlReport = "<table><tr><th>Product Name</th><th>Price</th></tr>";

        // Iterate through the list of products using foreach loop
        foreach (var product in products)
        {
            // Add product information to the HTML report
            htmlReport += $"<tr><td>{product.Name}</td><td>${product.Price}</td></tr>";
        }

        // Close the table tag in the HTML report
        htmlReport += "</table>";

        // Create a new instance of the HtmlToPdf class
        var htmlToPdf = new ChromePdfRenderer();

        // Generate the PDF from the HTML report
        var PDF = htmlToPdf.RenderHtmlAsPdf(htmlReport);

        // Save the PDF to a file
        PDF.SaveAs("ProductReport.PDF");

        // Inform the user that the PDF has been generated
        Console.WriteLine("ProductReport.PDF has been generated.");
    }
}
using System;
using System.Collections.Generic;
using IronPdf;

class Program
{
    static void Main()
    {
        // Create a list of products
        List<Product> products = new List<Product>
        {
            new Product("Product A", 29.99m),
            new Product("Product B", 49.99m),
            new Product("Product C", 19.99m),
        };

        // Initialize an HTML string to store the report content
        string htmlReport = "<table><tr><th>Product Name</th><th>Price</th></tr>";

        // Iterate through the list of products using foreach loop
        foreach (var product in products)
        {
            // Add product information to the HTML report
            htmlReport += $"<tr><td>{product.Name}</td><td>${product.Price}</td></tr>";
        }

        // Close the table tag in the HTML report
        htmlReport += "</table>";

        // Create a new instance of the HtmlToPdf class
        var htmlToPdf = new ChromePdfRenderer();

        // Generate the PDF from the HTML report
        var PDF = htmlToPdf.RenderHtmlAsPdf(htmlReport);

        // Save the PDF to a file
        PDF.SaveAs("ProductReport.PDF");

        // Inform the user that the PDF has been generated
        Console.WriteLine("ProductReport.PDF has been generated.");
    }
}
$vbLabelText   $csharpLabel

C# For Each 迴圈(開發者使用方法)圖 1 - 輸出結果

結論

在本教程中,我們探討了"C# foreach"循環的基本原理、重要性、用例以及如何在程式碼中實現它。 我們還介紹了 IronPDF,這是一個功能強大的 C# 庫,用於處理 PDF 文件,並演示瞭如何將foreach循環與 IronPDF 結合使用,根據數據集合生成 PDF 報告。

不斷學習和提陞技能,你很快就能充分利用foreach循環和其他 C# 功能,創建強大而高效的應用程式。 IronPDF 提供免費試用版,供用戶測試圖庫。 如果您決定購買,IronPDF 授權起價為$799 。

常見問題解答

C# 中的 foreach 迴圈是什麼?

C# 的 foreach 迴圈是一種程式設計結構,它簡化了遍歷數組、列表和字典等集合的過程。它允許開發人員以簡潔易讀的方式對集合中的每個元素執行操作,而無需管理索引或計數。

如何使用 C# 中的 foreach 循環建立 PDF 報告?

您可以將 foreach 迴圈與 IronPDF 結合使用來產生 PDF 報告。透過遍歷資料集合(例如產品清單),您可以動態建立 HTML 報告字串,然後使用 IronPDF 的ChromePdfRenderer將其轉換為 PDF。

C# foreach 迴圈有哪些應用場景?

foreach 迴圈的常見用例包括對集合中的值求和、搜尋項目、修改元素以及對集合中的每個元素執行操作。

C# 中的 foreach 迴圈與 for 迴圈有何不同?

foreach 迴圈因其可讀性和簡潔性而備受青睞。與 for 迴圈不同,它不需要手動管理集合的索引或計數。 foreach 迴圈最適合用於唯讀迭代。

如何在 foreach 迴圈中使用 var 關鍵字?

您可以在 foreach 迴圈中使用 var 關鍵字,讓編譯器推斷集合中元素的資料類型,讓程式碼更簡潔、更容易維護。

使用 foreach 迴圈時,可以修改集合嗎?

由於可能出現運行時錯誤,foreach 迴圈不適合在迭代過程中修改集合。如果需要修改,請考慮使用 for 迴圈或建立一個新的修改後的集合。

如何在 C# 中使用 foreach 迴圈處理字典迭代?

在 C# 中,你可以使用 foreach 迴圈遍歷字典,並利用KeyValuePair結構有效率地存取鍵和值。

foreach 迴圈可以遍歷哪些類型的集合?

foreach 迴圈可以遍歷任何實作了 IEnumerable 或 IEnumerable 介面的集合。接口。這包括 C# 中的陣列、列表、字典和其他集合類型。

C# 中 foreach 迴圈的語法是什麼?

C# 中 foreach 迴圈的語法為: foreach (variableType variableName in collection) { // Code to execute for each item }其中 variableType 是資料類型,variableName 是迴圈變量,collection 是正在迭代的集合。

如何在 C# 專案中安裝 PDF 庫?

可以透過新增 IronPDF NuGet 套件將 IronPDF 安裝到 C# 專案中。安裝說明請參閱 IronPDF 文件。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。