.NET 帮助

C# For Each(开发人员如何使用它)

在本教程中,我们将介绍开发人员的必备工具 "C# foreach "循环。 foreach循环简化了遍历集合的过程,使得在每个项目上执行操作变得更加容易,而无需担心底层细节。 我们将讨论foreach的重要性、它的使用案例以及如何在您的C#代码中实现它。

foreach 循环介绍

foreach 循环是开发人员以简洁和可读的方式遍历集合的强大工具。 它简化了代码,减少了出错的机会,因为无需手动管理索引或集合项的计数。 在变量声明方面,foreach 循环有五个变量声明,而 for 循环只有三个变量声明。

foreach 的用例包括:

  • 汇总集合中的值
  • 在集合中搜索项目
  • 修改集合中的元素
  • 对集合的每个元素执行操作

理解集合

C# 中有不同类型的集合,用于在单个对象中存储一组项目。 这些工具包括数组、列表、字典等。 foreach 循环是一个有用的工具,可以用于任何实现了 IEnumerable 或 IEnumerable 接口的集合。

一些常见的集合类型包括

  • 数组:具有相同数据类型的固定大小的元素集合。
  • 列表:具有相同数据类型的元素的动态集合。
  • 字典:键值对的集合,其中每个键都是唯一的。

    System.Collections.Generic 命名空间包含 ForEach 扩展方法,可以与任何内置集合类一起使用。

在 C# 中实现 foreach 语句;

现在,我们对集合和 for each 循环有了基本的了解,下面让我们深入了解其语法,看看它在 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
$vbLabelText   $csharpLabel

在这里,variableType 代表集合中项目的数据类型,variableName 是在循环中给当前项目(循环变量)指定的名称,而 collection 指的是您想要遍历的集合。

示例

举个例子,我们有一个整数列表,想要求列表中所有元素的和。


    using System;
    using System.Collections.Generic;

            // 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 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<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 for each loop
            foreach (int number in numbers)
            {
                sum += number;
            }

            // Print the sum
            Console.WriteLine("The sum of the elements is: " + sum);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

输出

当循环执行时,输出结果如下。


    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
$vbLabelText   $csharpLabel

在上面的示例中,我们首先创建一个名为numbers的整数列表,并初始化一个变量sum来存储元素的和。 然后,我们使用 foreach 循环遍历列表,并将每个元素的值加到总和中。 最后,我们将总和打印到控制台。 我们还可以使用类似的 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
$vbLabelText   $csharpLabel

遍历字典: 当使用for each循环遍历字典时,您需要使用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 和 for each:LINQ(Language Integrated Query,语言集成查询)是 C# 中的一个强大功能,它允许您以更具声明性的方式查询和操作数据。 您可以将LINQ与 for each 循环结合使用,以创建更具表现力和效率的代码。

示例:


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

    using System;
    using System.Collections.Generic;
    using System.Linq;
            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 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(Of Integer) 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
$vbLabelText   $csharpLabel

将IronPDF功能添加到每个C#教程

在本节中,我们将扩展我们的 "C# for each "循环教程,介绍 IronPDF,这是一个在 C# 中处理 PDF 文件的流行库。 我们将演示如何将 foreach 循环与 IronPDF 结合使用,根据数据集合生成 PDF 报告。

IronPDF 介绍

IronPDF 文档 是一个强大的库,用于在 C# 中创建、编辑和提取 PDF 文件的内容。 它为处理 PDF 文档提供了易于使用的 API,是需要将 PDF 功能纳入其应用程序的开发人员的绝佳选择。

IronPDF 的一些主要功能包括

安装 IronPDF

要开始使用 IronPDF,您需要安装 IronPDF NuGet 软件包。 您可以按照安装 IronPDF中的说明进行操作。

使用 IronPDF 生成 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
$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 和 for each 循环来生成包含产品信息的 PDF 报告:


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

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

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

	' Create a list of products
	Private 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
	Private htmlReport As String = "<table><tr><th>Product Name</th><th>Price</th></tr>"

	' Iterate through the list of products using for each 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.")
$vbLabelText   $csharpLabel

C# For Each(对开发人员的工作原理)图 1 - 输出结果

结论

在整个教程中,我们探讨了 "C# for each "循环的基本原理、其重要性、用例以及如何在代码中实现它。 我们还介绍了 IronPDF(一个功能强大的库,用于在 C# 中处理 PDF 文件),并演示了如何将 for each 循环与 IronPDF 结合使用,根据数据集合生成 PDF 报告。

不断学习和积累技能,您很快就能充分发挥 for each 循环和其他 C# 功能的潜力,创建强大而高效的应用程序。 IronPDF提供免费试用以测试该库。 如果您决定购买,IronPDF 许可证的起价为 $749。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C#字符串替换(开发人员如何使用)
下一步 >
C#中的Try/Catch(开发者如何使用)