
C# For Each (開発者向けの仕組み)
このチュートリアルでは、開発者にとっての必須ツールである"C# foreach"ループについて解説します。 foreachループはコレクションを反復処理するプロセスを簡素化し、基盤となる詳細について心配することなく各項目に対して操作を実行しやすくします。 当社ではforeachの重要性、その使用ケース、およびC#コード内での実装方法について説明します。
foreachループの紹介
foreachループは、開発者がコレクションを簡潔にかつ可読性のある方法で反復処理するための強力なツールです。 コードを簡素化し、インデックスやコレクションアイテムの数を手動で管理する必要がないため、エラーの可能性を減少させます。 可読性と単純さの点で、forループよりも好まれることがよくあります。
foreachの使用例としては次のものが含まれます:
- コレクション内の値の合計を算出する
- コレクション内のアイテムを検索する
- コレクション内の要素を変更する
- コレクションの各要素に対して操作を行う
コレクションの理解
C#には、1つのオブジェクトにグループ化されたアイテムを格納するために使用されるさまざまなタイプのコレクションがあります。 これには配列、リスト、ディクショナリなどが含まれます。 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ここでは、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
上記の例では、まず整数のリストをsumを初期化します。 次に、foreachループを使用してリストを反復処理し、各要素の値を合計に追加します。 最後に、コンソールに合計を出力します。 このメソッドは、他のコレクションに対して同様に印刷または操作するように適応することもできます。
バリエーションとベストプラクティス
foreachループの使い方の基本的な理解が得られたので、いくつかのバリエーションとベストプラクティスについて話し合いましょう。
読み取り専用の反復処理:foreachループは読み取り専用の反復処理に最適で、反復中にコレクションを変更すると予期しない結果やランタイムエラーを引き起こす可能性があります。 反復中にコレクションを変更する必要がある場合は、従来のforループを使用するか、必要な変更を加えた新しいコレクションを作成することを検討してください。
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辞書の反復処理:辞書を反復処理するには、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 ClassC#foreachチュートリアルにIronPDF機能を追加する
このセクションでは、"C# foreach"ループのチュートリアルに、C#でPDFファイルを操作するための人気のあるライブラリであるIronPDFを導入します。 foreachループとIronPDFを組み合わせて、データのコレクションに基づいてPDFレポートを生成する方法を示します。
IronPDF の紹介
IronPDFはC#でPDFファイルを作成、編集、コンテンツを抽出するための強力なライブラリです。 PDFドキュメントを扱うための使いやすいAPIを提供し、アプリケーションに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 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次に、PDFレポートを生成するためのProductオブジェクトのリストを作成しましょう:
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"ループの基本、重要性、使用例、およびコードへの実装方法について探求しました。 また、C#でPDFファイルを操作するための強力なライブラリであるIronPDFを紹介し、データのコレクションに基づいてPDFレポートを生成するためにforeachループとIronPDFを組み合わせて使用する方法を示しました。
学び続けスキルを構築していくと、foreachループや他のC#機能のフルポテンシャルを活用して、堅牢で効率的なアプリケーションを作成できるようになります。 IronPDFは、ライブラリをテストするための無料トライアルを提供しています。 購入を決定した場合、IronPDFライセンスは$999から始まります。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。
関連する記事


