跳過到頁腳內容
.NET幫助

C# For Each(開發者的工作原理)

在本教程中,我們將介紹開發人員必備的工具"C# foreach"循環。 foreach 環路簡化了在一個集合中進行迭代的過程,讓您可以更輕鬆地對每個項目執行操作,而不必擔心底層的細節。 我們將討論 foreach 的重要性、其使用案例,以及如何在您的 C# 程式碼中實作。

foreach循環簡介

foreach 環路是開發人員以簡潔、可讀的方式迭代集合的強大工具。 由於不需要手動管理索引或集合項目的計數,因此可以簡化程式碼並降低出錯的機會。 就可讀性和簡易性而言,foreach 環路通常比傳統的 for 環路更受歡迎。

foreach 的使用案例包括:

  • 總結集合中的值
  • 在集合中搜尋項目
  • 修改集合中的元素
  • 對集合的每個元素執行動作

瞭解集合

C# 中有不同類型的集合,用來在單一物件中儲存一組項目。 這些工具包括陣列、列表、字典等。 foreach 環路是一個有用的工具,可以用於任何實作 IEnumerableIEnumerable<T> 介面的集合。

一些常見的集合類型包括

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

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
}
For Each variableName As variableType In collection
	' Code to execute for each item
Next variableName
$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);
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		' Create a list of integers
		Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}

		' Initialize a variable to store the sum
		Dim sum As Integer = 0

		' Iterate through the list using foreach loop
		For Each number As Integer In numbers
			sum += number
		Next number

		' Print the sum
		Console.WriteLine("The sum of the elements is: " & sum)
	End Sub
End Class
$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);
}
For Each number In numbers
	Console.WriteLine(number)
Next 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.");
}
Dim ageDictionary As New Dictionary(Of String, Integer) From {
	{"Alice", 30},
	{"Bob", 25},
	{"Charlie", 22}
}

For Each entry As KeyValuePair(Of String, Integer) In ageDictionary
	Console.WriteLine($"{entry.Key} is {entry.Value} years old.")
Next entry
$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);
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq

Friend Class Program
	Shared Sub Main()
		Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}

		' Use LINQ to filter out even numbers
		Dim evenNumbers = numbers.Where(Function(n) n Mod 2 = 0)

		' Iterate through the even numbers using foreach loop
		For Each number In evenNumbers
			Console.WriteLine(number)
		Next number
	End Sub
End Class
$vbLabelText   $csharpLabel

在 C# foreach 教程中添加 IronPDF 功能。

在本節中,我們將透過介紹 IronPDF(一個用於在 C# 中處理 PDF 檔案的常用函式庫)來延展我們關於 "C# foreach "循環的教學。 我們將示範如何結合 IronPDF 使用 foreach 環路來根據資料集合產生 PDF 報告。

IronPDF 簡介

IronPDF 是一個功能強大的函式庫,可用於在 C# 中建立、編輯 PDF 檔案,以及從 PDF 檔案中擷取內容。 它提供了易於使用的 API 來處理 PDF 文件,使其成為需要將 PDF 功能整合到應用程式中的開發人員的絕佳選擇。

IronPdf 的一些主要功能包括:

  • 從 HTML、URL 和影像產生 PDF
  • 編輯現有的 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;
    }
}
Public Class Product
	Public Property Name() As String
	Public Property Price() As Decimal

	Public Sub New(ByVal name As String, ByVal price As Decimal)
		Me.Name = name
		Me.Price = price
	End Sub
End Class
$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),
};
Dim products As New List(Of Product) From {
	New Product("Product A", 29.99D),
	New Product("Product B", 49.99D),
	New Product("Product C", 19.99D)
}
$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.");
    }
}
Imports System
Imports System.Collections.Generic
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Create a list of products
		Dim products As New List(Of Product) From {
			New Product("Product A", 29.99D),
			New Product("Product B", 49.99D),
			New Product("Product C", 19.99D)
		}

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

		' Iterate through the list of products using foreach loop
		For Each product In products
			' Add product information to the HTML report
			htmlReport &= $"<tr><td>{product.Name}</td><td>${product.Price}</td></tr>"
		Next product

		' Close the table tag in the HTML report
		htmlReport &= "</table>"

		' Create a new instance of the HtmlToPdf class
		Dim htmlToPdf = New ChromePdfRenderer()

		' Generate the PDF from the HTML report
		Dim 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.")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# For Each (How It Works For Developers) 圖 1 - Output Result

結論

在本教程中,我們探討了 "C# foreach "循環的基本原理、其重要性、使用案例,以及如何在您的程式碼中實作。 我們還介紹了 IronPDF,這是一個用 C# 處理 PDF 檔案的功能強大的函式庫,並示範了如何結合 IronPDF 使用 foreach 環路,根據資料集合產生 PDF 報告。

持續學習並建立您的技能,您很快就能充分發揮 foreach 環路和其他 C# 功能的潛力,建立強大且有效率的應用程式。 IronPDF 提供免費試用以測試該函式庫。 如果您決定購買,IronPDF 授權從 $799 起。

常見問題解答

什麼是 C# foreach 環路?

C# foreach 環路是一種程式結構,它簡化了在陣列、列表和字典等集合中進行迭代的過程。它允許開發人員以簡明易懂的方式對集合中的每個項目執行操作,而無需管理索引或計數。

如何在 C# 中使用 foreach 環路建立 PDF 報表?

您可以結合 IronPDF 使用 foreach 循環來產生 PDF 報告。透過迭代資料集合,例如產品清單,您可以動態地建立 HTML 報表字串,然後再使用 IronPDF 的 ChromePdfRenderer 將其轉換成 PDF。

C# foreach 環路有哪些使用案例?

foreach 環路的常見用例包括求集合中的值、搜尋項目、修改元素,以及對集合中的每個元素執行動作。

foreach 環路與 C# 中的 for 環路有何不同?

Foreach 環路因其可讀性和簡單性而受到青睞。與 for 環路不同,它不需要手動管理集合的索引或數量。foreach 循環最適合用於唯讀迭代。

如何在 foreach 環路中使用 var 關鍵字?

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

您可以在使用 foreach 循環時修改集合嗎?

由於可能發生執行時錯誤,foreach 環路不適合在迭代過程中修改集合。如果需要修改,請考慮使用 for 環路或建立新的修改集合。

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

在 C# 中,您可以利用 KeyValuePair 結構有效地存取鍵和值,使用 foreach 循環遍歷字典。

foreach 環路可以遍歷哪些類型的集合?

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

C# 中 foreach 環路的語法是什麼?

C# 中 foreach 環路的語法為foreach (variableType variableName in collection) { // 為每個項目執行的程式碼 } 其中 variableType 是資料類型,variableName 是迴圈變數,collection 是正在迭代的集合。

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

IronPDF 可透過加入 IronPDF NuGet 套件安裝在 C# 專案中。IronPDF 文件中提供了安裝說明。

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

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

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

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。