.NET 帮助

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

发布 2023年五月16日
分享:

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

foreach 循环简介

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

foreach 循环的用例包括

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

了解收藏

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

常见的集合类型包括

  • 数组:具有相同数据类型的固定大小的元素集合。
  • 列表数据类型相同的元素动态集合。

  • 字典键值对的集合,其中每个键都是唯一的。

System.Collections.Generic "命名空间包含 "ForEach "扩展方法,可用于任何内置的集合类。

在 C&num 中执行 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
VB   C#

变量类型 "代表集合中项目的数据类型,"变量名 "是循环中当前项目的名称 (循环变量),而 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 来存储元素的 "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
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 Tutorial 中

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

IronPDF 简介

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

IronPDF 的一些主要功能包括

  • 从 HTML 生成 PDF、URL 和图像
  • 编辑现有的 PDF 文档
  • 从 PDF 文件中提取文本和图像
  • 为 PDF 添加注释、表单字段和加密

安装 IronPDF

要开始使用 IronPDF,您需要安装 IronPDF NuGet 软件包。在项目目录中运行以下命令即可完成安装:

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

接下来,让我们创建一个产品对象列表来生成 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.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >