.NET 幫助

C# For Each(開發人員如何運作)

發佈 2023年5月16日
分享:

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

foreach迴圈介紹

foreach迴圈是一個強大的工具,讓開發者能夠以簡潔且易讀的方式遍歷集合。它簡化了程式碼並減少錯誤發生的機會,因為不必手動管理集合項目的索引或計數。就變數宣告而言,foreach迴圈有五個變數宣告,而for迴圈只有三個變數宣告。

foreach的使用案例包括:

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

理解集合

C# 中有不同類型的集合被用來將一組項目存儲在一個單獨的對象中。這些集合包括數組、列表、字典等。foreach 迴圈是一個有用的工具,可以與任何實現了 IEnumerable 或 IEnumerable接口的集合一起使用。

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

  • 數組:固定大小的元素集合,所有元素具有相同的數據類型。
  • 列表:動態大小的元素集合,所有元素具有相同的數據類型。
  • 字典:由鍵值對組成的集合,每個鍵都是唯一的。

System.Collections.Generic 命名空間包含 ForEach 擴展方法,可以與任何內置集合類一起使用。

在 C# 中實現 foreach 語句

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

For Each 迴圈語法


    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
VB   C#

在這裡, variableType 代表集合中項目的數據類型,variableName 是在循環中給當前項目賦予的名稱 (迴圈變數),collection 指的是您想要遍歷的集合。

例子

讓我們考慮一個例子,我們有一個整數列表,並且我們想找出列表中所有元素的總和。


    using System;
    using System.Collections.Generic;

            // Create a list of integers
            List numbers = new List { 1, 2, 3, 4, 5 };

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

            // Iterate through the list using for each 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;

            // Create a list of integers
            List numbers = new List { 1, 2, 3, 4, 5 };

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

            // Iterate through the list using for each 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

			' Create a list of integers
			Private numbers As New List From {1, 2, 3, 4, 5}

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

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

			' Print the sum
			Console.WriteLine("The sum of the elements is: " & sum)
VB   C#

輸出

當迴圈執行時,會產生以下輸出。


    The sum of the elements is: 15

    The sum of the elements is: 15
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'The sum @of the elements is: 15
VB   C#

在上面的範例中,我們首先創建一個名為 numbers 的整數列表,並初始化一個變數 sum 來儲存元素的總和。然後,我們使用 foreach 循環來遍歷列表並將每個元素的值加到 sum 中。最後,我們將 sum 打印到控制台。我們也可以使用 foreach 循環來類似地列印一個陣列。

變化和最佳實踐

現在我們對於如何使用 for each 迴圈有了基本的了解,讓我們來討論一些變化和最佳實踐。

唯讀迭代:for each 迴圈最適合用於唯讀迭代,因為在迭代時修改集合可能會導致意想不到的結果或運行時錯誤。如果需要在迭代期間修改集合,請考慮使用傳統的 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
VB   C#

遍歷字典: 當使用 for each 迴圈遍歷字典時,您需要使用 KeyValuePair 結構。這個結構代表字典中的鍵值對。

範例:


    Dictionary ageDictionary = new Dictionary
    {
        { "Alice", 30 },
        { "Bob", 25 },
        { "Charlie", 22 }
    };

    foreach (KeyValuePair entry in ageDictionary)
    {
        Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
    }

    Dictionary ageDictionary = new Dictionary
    {
        { "Alice", 30 },
        { "Bob", 25 },
        { "Charlie", 22 }
    };

    foreach (KeyValuePair entry in ageDictionary)
    {
        Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
    }
Dim ageDictionary As New Dictionary From {
	{ "Alice", 30 },
	{ "Bob", 25 },
	{ "Charlie", 22 }
}

	For Each entry As KeyValuePair In ageDictionary
		Console.WriteLine($"{entry.Key} is {entry.Value} years old.")
	Next entry
VB   C#

LINQ 和 for each: LINQ (語言集成查詢) 是 C# 中的一項強大功能,允許您以更具聲明性的方式查詢和操作數據。您可以將 LINQ 用於 for each 循環,以創建更具表達性和高效的代碼。

例子:


    using System;
    using System.Collections.Generic;
    using System.Linq;
            List numbers = new List { 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 for each loop
            foreach (var number in evenNumbers)
            {
                Console.WriteLine(number);
            }

    using System;
    using System.Collections.Generic;
    using System.Linq;
            List numbers = new List { 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 for each loop
            foreach (var number in evenNumbers)
            {
                Console.WriteLine(number);
            }
Imports System
	Imports System.Collections.Generic
	Imports System.Linq
			Private numbers As New List From {1, 2, 3, 4, 5}

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

			' Iterate through the even numbers using for each loop
			For Each number In evenNumbers
				Console.WriteLine(number)
			Next number
VB   C#

將 IronPDF 功能添加到 C# for each 教程中

在本節中,我們將通過引入 IronPDF(在 C# 中處理 PDF 文件的流行庫)來擴展我們關於 "C# for each" 循環的教程。我們將演示如何結合使用 foreach 循環與 IronPDF,基於數據集合生成 PDF 報告。

IronPDF 介紹

IronPDF 是一個強大的庫,能夠在 C# 中創建、編輯和提取 PDF 文件的內容。它提供了易於使用的 API 來處理 PDF 文檔,使其成為需要將 PDF 功能集成到其應用程序中的開發人員的一個極好選擇。

IronPDF 的一些主要功能包括:

  • 從 HTML 生成 PDF, 網址 和 圖片
  • 編輯現有的 PDF 文件
  • 從 PDF 提取文字和圖片
  • 添加註釋、表單欄位和加密到 PDF

安裝 IronPDF

要開始使用 IronPDF,您需要安裝 IronPDF NuGet 套件。您可以在您的項目目錄中運行以下命令來完成此操作:

Install-Package IronPdf

使用 IronPDF 和 for each 生成 PDF 報告

在本範例中,我們將使用 IronPDF 庫和 for each 迴圈來創建包含產品名稱和價格的產品列表的 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
VB   C#

接下來,讓我們建立一個 Product 物件列表來生成 PDF 報告:


    List products = new List
    {
        new Product("Product A", 29.99m),
        new Product("Product B", 49.99m),
        new Product("Product C", 19.99m),
    };

    List products = new List
    {
        new Product("Product A", 29.99m),
        new Product("Product B", 49.99m),
        new Product("Product C", 19.99m),
    };
Dim products As New List From {
	New Product("Product A", 29.99D),
	New Product("Product B", 49.99D),
	New Product("Product C", 19.99D)
}
VB   C#

現在,我們可以使用IronPDF和for each迴圈來生成包含產品信息的PDF報告:


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

    // Create a list of products
    List products = new List
    {
        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 = "Product ReportNamePrice";

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

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

    // 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;

    // Create a list of products
    List products = new List
    {
        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 = "Product ReportNamePrice";

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

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

    // 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

	' Create a list of products
	Private products As New List 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
	Private htmlReport As String = "Product ReportNamePrice"

	' Iterate through the list of products using for each loop
	For Each product In products
		' Add product information to the HTML report
		htmlReport &= $"{product.Name}${product.Price}"
	Next product

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

	' 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.")
VB   C#

C# For Each(開發者如何使用)圖1 - 輸出結果

結論

在本教程中,我們探討了 "C# for each" 迴圈的基本原理、其重要性、使用情境以及如何在您的代碼中實現它。我們還介紹了IronPDF,這是一個強大的用於處理C#中PDF文件的庫,並演示了如何結合使用for each迴圈和IronPDF來基於數據集合生成PDF報告。

繼續學習並提升您的技能,您將很快能夠利用for each迴圈和其他C#功能的全部潛力來創建穩健且高效的應用程式。IronPDF提供了 免費試用 用於測試該庫。如果您決定購買,IronPDF 授權從 $749 開始。

< 上一頁
C# 字符串替換(開發人員如何運作)
下一個 >
C# 中的 Try/Catch(開發者的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >