C# For Each(開發者的工作原理)
在本教程中,我們將介紹"C# foreach"迴圈,這是開發人員的重要工具。 foreach 迴圈簡化了遍歷集合的過程,使其更容易對每個項目執行操作,而無需擔心底層細節。 我們將討論 foreach 的重要性、其使用案例以及如何在您的C#程式碼中實施它。
介紹 foreach 迴圈
foreach 迴圈是一個強大的工具,讓開發人員以簡潔且可讀的方式遍歷集合。 它簡化了程式碼並減少了錯誤的可能性,因為無需手動管理集合項目的索引或數量。 在可讀性和簡潔性方面,foreach 迴圈通常比傳統的 for 迴圈更受歡迎。
foreach 的使用案例包括:
- 集合中的值求和
- 在集合中搜尋項目
- 修改集合中的元素
- 對集合的每個元素執行操作
理解集合
在C#中有不同型別的集合,用於在單個物件中儲存一組項目。 這些包括陣列、列表、字典等。 foreach 迴圈是一個有用的工具,可以用於任何實現 IEnumerable 或 IEnumerable<t> 介面的集合。
一些常見的集合型別包括:
- 陣列:具有相同資料型別的固定大小元素集合。
- 列表:具有相同資料型別的動態元素集合。
- 字典:鍵值對集合,其中每個鍵是唯一的。
System.Collections.Generic 程式庫命名空間包含用於操作集合的各種型別。
Implementing the foreach statement in C#
現在我們已經對集合和 foreach 迴圈有了基本的了解,讓我們深入研究語法並了解它在C#中的工作原理。
foreach 迴圈的語法
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 variableNameFor 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 ClassImports 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 迴圈最適合只讀迭代,因為在迭代時修改集合可能會導致意外結果或運行時錯誤。 如果您需要在迭代期間修改集合,請考慮使用傳統的 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 numberFor 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 entryDim 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 entryLINQ 和 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 ClassImports 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# 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 ClassPublic 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)
}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 ClassImports 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。
Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。