跳過到頁腳內容
.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

將 IronPDF 功能添加到 C# foreach 教程

在本節中,我們將通過引入 IronPDF 來擴展我們的 "C# foreach" 迴圈教程,這是一個用於在 C# 中處理 PDF 文件的流行庫。 我們將展示如何將 foreach 迴圈與 IronPDF 結合使用,以根據數據集合生成 PDF 報告。

IronPDF 的介紹

IronPDF 是一個強大的庫,用於創建、編輯和提取 C# 中 PDF 文件的內容。 它提供了易於使用的 API,適合需要在其應用程式中集成 PDF 功能的開發人員。

IronPDF 的一些主要功能包括:

  • 從 HTML、網址和圖像生成 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(開發人員如何使用) 圖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 迴圈適用於只讀迭代。

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

您可以在 foreach 迴圈中使用 var 關鍵字,使編譯器推斷集合中元素的數據類型,從而使代碼更加簡潔且更易於維護。

在使用 foreach 迴圈的過程中可以修改集合嗎?

foreach 迴圈不適合在迭代期間修改集合,因為這可能會導致運行時錯誤。如果需要修改,請考慮使用 for 迴圈或創建一個新的修改後的集合。

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

在 C# 中,您可以使用 foreach 迴圈結合 KeyValuePair 結構高效地迭代字典,以訪問鍵和值。

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

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

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

C# 中 foreach 迴圈的語法是:foreach (variableType variableName in collection) { // 每項目執行的代碼 },其中 variableType 是數據類型,variableName 是循環變數,collection 是被迭代的集合。

如何在 C# 項目中安裝 PDF 庫?

可以通過添加 IronPDF NuGet 包在 C# 項目中安裝 IronPDF。安裝說明可在 IronPDF 文檔中找到。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。