跳至頁尾內容
開發者更新

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

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

介紹 foreach 迴圈

foreach 迴圈是一個強大的工具,讓開發人員以簡潔且可讀的方式遍歷集合。 它簡化了程式碼並減少了錯誤的可能性,因為無需手動管理集合項目的索引或數量。 在可讀性和簡潔性方面,foreach 迴圈通常比傳統的 for 迴圈更受歡迎。

foreach 的使用案例包括:

  • 集合中的值求和
  • 在集合中搜尋項目
  • 修改集合中的元素
  • 對集合的每個元素執行操作

理解集合

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

一些常見的集合型別包括:

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

System.Collections.Generic 程式庫命名空間包含用於操作集合的各種型別。

Implementing the foreach statement in C

現在我們已經對集合和 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(Language Integrated Query)是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# foreach"迴圈教程,這是一個在C#中處理PDF文件的流行程式庫。 我們將演示如何將 foreach 迴圈與IronPDF結合使用,根據資料集合生成PDF報告。

IronPDF 的介紹

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

IronPDF 的一些關鍵功能包括:

  • 從HTML、URLs和圖像生成PDFs
  • 編輯現有的PDF文件
  • 從PDFs中提取文字和圖像
  • 在PDFs中新增註釋、表單字段和加密

安裝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 授權起價為 $999。

常見問題

什麼是C# foreach 迴圈?

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

如何使用C#中的foreach迴圈來建立PDF報告?

您可以將foreach迴圈與IronPDF結合使用以生成PDF報告。通過遍歷一個資料集合,如產品列表,您可以動態建立一個HTML報告字串,然後使用IronPDF的ChromePdfRenderer將其轉換為PDF。

C# foreach 迴圈的用例有哪些?

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

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

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

如何將var關鍵字與foreach迴圈一起使用?

您可以在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包在C#項目中安裝IronPDF。安裝說明可在IronPDF文件中找到。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話