C# For Each(開發者的工作原理)
在本教程中,我們將介紹開發人員必備的工具"C# foreach"循環。 foreach 循環簡化了遍歷集合的過程,使用戶更容易對每個項目執行操作,而無需擔心底層細節。 我們將討論 foreach 的重要性、它的用例以及如何在 C# 程式碼中實現它。
foreach 循環簡介
foreach 迴圈是開發人員以簡潔易讀的方式遍歷集合的強大工具。 由於不需要手動管理索引或集合項目的計數,因此可以簡化程式碼並降低出錯的機會。 就可讀性和簡潔性而言,foreach 循環通常比傳統的 for 循環更受歡迎。
foreach 的使用案例包括:
- 總結集合中的值
- 在集合中搜尋項目
- 修改集合中的元素
- 對集合的每個元素執行動作
瞭解集合
C# 中有不同類型的集合,用來在單一物件中儲存一組項目。 這些工具包括陣列、列表、字典等。 foreach 循環是一個有用的工具,可以與任何實作了 IEnumerable 或 IEnumerable<t> 介面的集合一起使用。
一些常見的集合類型包括
- 陣列:具有相同資料類型的固定大小元素集合。
- 清單:具有相同資料類型的元素動態集合。
- 詞典:鍵值對的集合,其中每個鍵都是唯一的。
System.Collections.Generic 命名空間包含用於處理集合的各種類型。
在 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
這裡,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
輸出
當循環執行時,會產生以下輸出。
The sum of the elements is: 15
在上面的範例中,我們首先建立一個名為 numbers 的整數列表,並初始化一個變數 sum 來儲存元素的總和。 然後,我們使用 foreach 循環遍歷列表,並將每個元素的值加到總和中。 最後,我們將總和列印到控制台。 此方法也可適用於印刷或在其他合集中類似操作。
變體與最佳實務
現在我們已經基本了解如何使用 foreach 循環,接下來讓我們討論一些變體和最佳實踐。
只讀迭代: foreach 迴圈最適合只讀迭代,因為在迭代過程中修改集合可能會導致意外結果或執行時錯誤。 如果在迭代過程中需要修改集合,請考慮使用傳統的循環,或建立包含所需修改的新集合。
使用 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
遍歷字典:當使用 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
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
為 C# 新增 IronPDF 功能 foreach 教學課程
在本節中,我們將透過介紹 IronPDF(一個用於在 C# 中處理 PDF 檔案的常用函式庫)來延展我們關於 "C# foreach "循環的教學。 我們將示範如何將 foreach 循環與 IronPDF 結合使用,根據資料集合產生 PDF 報告。
IronPDF 簡介
IronPDF 是一個功能強大的函式庫,可用於在 C# 中建立、編輯 PDF 檔案,以及從 PDF 檔案中擷取內容。 它提供了易於使用的 API 來處理 PDF 文件,使其成為需要將 PDF 功能整合到應用程式中的開發人員的絕佳選擇。
IronPDF 的一些主要功能包括:
- 從 HTML、URL 和影像產生 PDF
- 編輯現有的 PDF 文件
- 從 PDF 擷取文字與圖片
- 在 PDF 中加入註解、表單欄位和加密功能
安裝 IronPDF。
要開始使用 IronPDF,您需要安裝 IronPDF NuGet 套件。 您可以按照 IronPDF 文檔中的說明進行翻譯。
使用 IronPDF 產生 PDF 報告 foreach
在這個範例中,我們將使用 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
接下來,我們建立一個 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)
}
現在,我們可以使用 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

結論
在本教程中,我們探討了 "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 迴圈不需要對集合的索引或計數進行手動管理。foreach 迴圈適用於只讀迭代。
如何在 foreach 迴圈中使用 var 關鍵字?
您可以在 foreach 迴圈中使用 var 關鍵字,使編譯器推斷集合中元素的數據類型,從而使代碼更加簡潔且更易於維護。
在使用 foreach 迴圈的過程中可以修改集合嗎?
foreach 迴圈不適合在迭代期間修改集合,因為這可能會導致運行時錯誤。如果需要修改,請考慮使用 for 迴圈或創建一個新的修改後的集合。
如何使用 foreach 迴圈處理 C# 中的字典迭代?
在 C# 中,您可以使用 foreach 迴圈結合 KeyValuePair 結構高效地迭代字典,以訪問鍵和值。
foreach 迴圈可以遍歷哪些類型的集合?
foreach 循環可以迭代任何實作 IEnumerable 或 IEnumerable
C# 中 foreach 迴圈的語法是什麼?
C# 中 foreach 迴圈的語法是:foreach (variableType variableName in collection) { // 每項目執行的代碼 },其中 variableType 是數據類型,variableName 是循環變數,collection 是被迭代的集合。
如何在 C# 項目中安裝 PDF 庫?
可以通過添加 IronPDF NuGet 包在 C# 項目中安裝 IronPDF。安裝說明可在 IronPDF 文檔中找到。



