.NET ヘルプ

C# For Each(開発者向けの仕組み)

更新済み 5月 16, 2023
共有:

このチュートリアルでは、開発者にとって重要なツールである「C# foreach」ループについて説明します。 foreachループは、コレクションを繰り返し処理するプロセスを簡略化し、各項目に対して操作を行う際に基礎的な詳細を気にせずに操作を容易にします。 foreach の重要性、その使用例、およびC#コードへの実装方法について説明します。

foreach ループの紹介

foreach ループは、開発者がコレクションを簡潔かつ読みやすい形で反復処理するための強力なツールです。 それはコードを簡略化し、コレクションアイテムのインデックスやカウントを手動で管理する必要がないため、エラーの可能性を減らします。 変数宣言に関しては、foreachループには5つの変数宣言があり、一方でforループには3つの変数宣言しかありません。

foreach のユースケースには以下が含まれます:

  • コレクション内の値を合計する
  • コレクション内のアイテムを検索
  • コレクション内の要素を変更する
  • コレクションの各要素に対してアクションを実行する

コレクションの理解

C#には、アイテムのグループを1つのオブジェクトに格納するために使用されるさまざまな種類のコレクションがあります。 これらには配列、リスト、辞書などが含まれます。 foreach ループは、IEnumerable または IEnumerable インターフェイスを実装する任意のコレクションで使用できる便利なツールです。

いくつかの一般的なコレクションタイプには以下が含まれます:

  • 配列: 同じデータ型の要素を固定サイズで集めたコレクション。
  • リスト: 同じデータ型の要素を動的に収集するコレクション。

  • 辞書: 各キーが一意であるキーと値のペアのコレクション。

    System.Collections.Generic 名前空間には、任意の組み込みコレクションクラスで使用できる ForEach 拡張メソッド が含まれています。

C#におけるforeach文の実装

コレクションとforeachループの基本的な理解ができたところで、次に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#

ここで、variableType はコレクション内の項目のデータ型を表し、variableName はループ内の現在の項目に与えられた名前です。 (ループ変数)そして、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 を初期化して要素の合計を格納します。 それから、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およびforeach: LINQ (言語統合クエリ (Language Integrated Query)) C#の強力な機能であり、データをより宣言的な方法でクエリおよび操作することができます。 for eachループでLINQを使用することで、より表現力があり効率的なコードを作成できます。

例:


    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#

C# の for each チュートリアルに IronPDF 機能を追加する

このセクションでは、「C# for each」ループに関するチュートリアルを拡張し、C#でPDFファイルを扱うための人気ライブラリであるIronPDFを紹介します。 次に、データのコレクションに基づいて、IronPDFを使用してPDFレポートを生成するために、foreachループをどのように使用するかを示します。

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レポートを生成するためにProductオブジェクトのリストを作成しましょう。


    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」ループの基本、重要性、使用例、およびそれをコードに実装する方法について探求しました。 また、C#でPDFファイルを操作するための強力なライブラリであるIronPDFも紹介し、データのコレクションに基づいてPDFレポートを生成するために、for eachループをIronPDFと組み合わせて使用する方法を実演しました。

次々に学び続けスキルを磨けば、for each ループや他のC#機能の潜在能力を十分に引き出し、信頼性が高く効率的なアプリケーションを作成できるようになります。 IronPDFは提供します 無料試用 ライブラリのテストのために。 購入を決定された場合、IronPDFライセンスは $749 から始まります。

< 以前
C# 文字列置換 (開発者のための動作方法)
次へ >
C#におけるTry/Catch(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >