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#
现在我们已经对集合和循环有了基本的了解,让我们深入了解语法,看看它在 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 循环,接下来让我们讨论一些变体和最佳实践。
只读迭代:循环最适合只读迭代,因为在迭代过程中修改集合可能会导致意外结果或运行时错误。 如果在迭代过程中需要修改集合,请考虑使用传统的循环,或者创建一个包含所需修改的新集合。
使用 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# foreach"循环的教程,这是一款流行的用于处理C#中的PDF文件的库。 我们将演示如何结合 IronPDF 使用 foreach 循环,根据数据集合生成 PDF 报告。
IronPDF介绍
IronPDF是一个用于在C#中创建、编辑和提取PDF文件内容的强大库。 它提供了易于使用的API来处理PDF文档,是开发者希望在应用中添加PDF功能的绝佳选择。
IronPDF的一些关键特性包括:
- 从HTML、URL和图像生成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
接下来,我们创建一个 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 开始。




