C#印刷リスト: クイックチュートリアル
C# では、リストの印刷は一般的なタスクであり、さまざまな方法で実行できるため、柔軟性とカスタマイズ性が提供されます。 リストは C# の基本的なデータ構造であり、その内容を印刷できることは、デバッグ、ログ記録、またはユーザーへの情報の表示に不可欠です。
この記事では、 C# でリストを印刷するさまざまな方法について説明します。
C# におけるリストの基本
C#では、System.Collections.Generic ネームスペースの一部であり、アイテムのコレクションを扱う際の柔軟性と効率性を提供します。 次のコードは単純な数値リストを作成します。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
}
}
Imports System
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
End Sub
End Class
ループを使用してリストを印刷する
1. foreach ループを使用する
リストの要素を印刷する伝統的かつ簡単な方法は、foreach ループを使用することです。簡単な例を示します:
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine("Printing list using foreach loop:");
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine("Printing list using foreach loop:");
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Public Shared Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
Console.WriteLine("Printing list using foreach loop:")
For Each number In numbers
Console.WriteLine(number)
Next number
End Sub
End Class
この方法は簡潔で読みやすいため、ほとんどのシナリオに適しています。
2. for ループを使用する
インデックスをより細かく制御したり、条件に応じて要素を印刷したい場合は、for ループを利用できます。文字列リストの例を以下に示します:
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// Create list of strongly typed objects
List<string> colors = new List<string> { "Red", "Green", "Blue", "Yellow" };
Console.WriteLine("Printing list using for loop:");
for (int index = 0; index < colors.Count; index++)
{
Console.WriteLine($"Color at index {index}: {colors[index]}");
}
}
}
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// Create list of strongly typed objects
List<string> colors = new List<string> { "Red", "Green", "Blue", "Yellow" };
Console.WriteLine("Printing list using for loop:");
for (int index = 0; index < colors.Count; index++)
{
Console.WriteLine($"Color at index {index}: {colors[index]}");
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Public Shared Sub Main()
' Create list of strongly typed objects
Dim colors As New List(Of String) From {"Red", "Green", "Blue", "Yellow"}
Console.WriteLine("Printing list using for loop:")
For index As Integer = 0 To colors.Count - 1
Console.WriteLine($"Color at index {index}: {colors(index)}")
Next index
End Sub
End Class
このアプローチは、インデックスにアクセスする必要がある場合や、印刷中に特定のロジックを適用する場合に役立ちます。
リスト要素を逆順に印刷する
リストを逆順で印刷するには、Reverse メソッドを使用することで実現できます。 このメソッドは、リスト内の要素の順序を逆にして、反復処理して印刷できるようにします。
1. List.Reverseメソッドの使用
たとえば、Reverse メソッドを使ってリストを逆順に並べ、各要素を印刷することができます。
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Reverse();
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Reverse();
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Public Shared Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
numbers.Reverse()
For Each number In numbers
Console.WriteLine(number)
Next number
End Sub
End Class
2. LINQ OrderByDescending の使用
また、OrderByDescending メソッドをキーと共に使用して、LINQのジェネリッククラスから特定の要素のコレクションを並べ替えることができます:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var reversedNumbers = numbers.OrderByDescending(n => n);
foreach (var number in reversedNumbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var reversedNumbers = numbers.OrderByDescending(n => n);
foreach (var number in reversedNumbers)
{
Console.WriteLine(number);
}
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Friend Class Program
Public Shared Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
Dim reversedNumbers = numbers.OrderByDescending(Function(n) n)
For Each number In reversedNumbers
Console.WriteLine(number)
Next number
End Sub
End Class
要素の数を数えて出力する
リスト内の要素の数を数えることは一般的な操作です。 この目的には Count プロパティを使用できます。 カウントがわかれば、簡単に印刷できます。
1. List.Countプロパティの使用
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count;
Console.WriteLine($"Number of elements: {count}");
}
}
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count;
Console.WriteLine($"Number of elements: {count}");
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Public Shared Sub Main()
Dim names As New List(Of String) From {"Alice", "Bob", "Charlie"}
Dim count As Integer = names.Count
Console.WriteLine($"Number of elements: {count}")
End Sub
End Class
2. LINQ Countメソッドの使用
LINQ が優先される場合は、カウントにも使用できます。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count();
Console.WriteLine($"Number of elements: {count}");
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count();
Console.WriteLine($"Number of elements: {count}");
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Friend Class Program
Public Shared Sub Main()
Dim names As New List(Of String) From {"Alice", "Bob", "Charlie"}
Dim count As Integer = names.Count()
Console.WriteLine($"Number of elements: {count}")
End Sub
End Class
指定したインデックスのリスト要素を印刷する
指定されたインデックスの要素を印刷するには、そのインデックスのリストにアクセスする必要があります。 これにより、さまざまな場所にある要素にアクセスできるようになり、潜在的なインデックス範囲外のシナリオを処理できるようになります。
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<double> prices = new List<double> { 19.99, 29.99, 39.99 };
int indexToPrint = 1;
if (indexToPrint >= 0 && indexToPrint < prices.Count)
{
Console.WriteLine($"Element at index {indexToPrint}: {prices[indexToPrint]}");
}
else
{
Console.WriteLine("Index out of range.");
}
}
}
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<double> prices = new List<double> { 19.99, 29.99, 39.99 };
int indexToPrint = 1;
if (indexToPrint >= 0 && indexToPrint < prices.Count)
{
Console.WriteLine($"Element at index {indexToPrint}: {prices[indexToPrint]}");
}
else
{
Console.WriteLine("Index out of range.");
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Public Shared Sub Main()
Dim prices As New List(Of Double) From {19.99, 29.99, 39.99}
Dim indexToPrint As Integer = 1
If indexToPrint >= 0 AndAlso indexToPrint < prices.Count Then
Console.WriteLine($"Element at index {indexToPrint}: {prices(indexToPrint)}")
Else
Console.WriteLine("Index out of range.")
End If
End Sub
End Class
これらの例は、さまざまなシナリオでリスト要素を印刷するための基礎を提供します。 印刷に使用できる他の便利なメソッドは、list クラスが提供します。
いくつかの便利なメソッドは次のとおりです:
Remove:Remove()メソッドは、C#リスト内の最初の出現を削除します。RemoveAll:RemoveAll()メソッドは、指定された述語に基づいて要素を削除するために使用されます。RemoveRange:RemoveRange()メソッドは、指定されたインデックスとカウントパラメータに基づいて範囲の要素を削除します。Add:Add()メソッドは、リストの最後に1つの要素のみを追加できます。AddRange:AddRange()メソッドは、指定されたコレクションの要素を最後に追加できます。Clear:Clear()メソッドは、リストからすべての要素を削除します。Insert:Insert()メソッドは、リストに指定したインデックスに要素を挿入します。ForEach:ForEach()メソッドは、各要素に特定のアクションを実行するために使用されます。例えば、各リストの値を効率的に印刷することです。ToArray:ToArray()メソッドは、リストを新しい配列にコピーします。
これで、要件に最適なアプローチを選択し、C# コードの読みやすさと効率性を向上させることができます。
String.Join メソッド
String.Join メソッドは、リストの要素を指定された区切り文字で1つの文字列に連結する簡潔な方法を提供します。 これは、リストのフォーマットされた文字列表現を作成するのに役立ちます。
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = string.Join(", ", numbers);
Console.WriteLine(result);
}
}
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = string.Join(", ", numbers);
Console.WriteLine(result);
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Public Shared Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
Dim result As String = String.Join(", ", numbers)
Console.WriteLine(result)
End Sub
End Class
ここでは、リストの要素 numbers がカンマとスペースで区切られた文字列に連結され、フォーマットされた出力となります。 リスト要素を印刷する前に sort メソッドを使用することもできます。
高度なシナリオでの LINQ の使用
より複雑なシナリオでは、印刷する前に要素をフィルター、変換、またはフォーマットしたい場合、言語統合クエリ (LINQ) が役立ちます。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers));
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers));
}
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Friend Class Program
Public Shared Sub Main()
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
Dim evenNumbers As List(Of Integer) = numbers.Where(Function(n) n Mod 2 = 0).ToList()
Console.WriteLine("Even numbers: " & String.Join(", ", evenNumbers))
End Sub
End Class
この例では、LINQを使用して元のリストから偶数をフィルターアウトします。Where() メソッドはラムダ式と共に適用され、ToList() メソッドは結果を再びリストに変換するために使用されます。

カスタムオブジェクトとToString()メソッド
カスタムオブジェクトのリストを持っている場合、意味のある表現のためにオブジェクトクラスで ToString メソッドをオーバーライドすることをお勧めします。 次の例はその方法を示しています。
using System;
using System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"{Name}, {Age} years old";
}
}
class Program
{
public static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 }
};
foreach (Person person in people)
{
Console.WriteLine(person);
}
}
}
using System;
using System.Collections.Generic;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"{Name}, {Age} years old";
}
}
class Program
{
public static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 }
};
foreach (Person person in people)
{
Console.WriteLine(person);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Person
Public Property Name() As String
Public Property Age() As Integer
Public Overrides Function ToString() As String
Return $"{Name}, {Age} years old"
End Function
End Class
Friend Class Program
Public Shared Sub Main()
Dim people As New List(Of Person) From {
New Person With {
.Name = "Alice",
.Age = 30
},
New Person With {
.Name = "Bob",
.Age = 25
}
}
For Each person As Person In people
Console.WriteLine(person)
Next person
End Sub
End Class
ToString() メソッドを Person クラスでオーバーライドすることにより、クラスのインスタンスが文字列として表現される方法を制御できます。 これにより、印刷したときにリストが読みやすくなります。

IronPrint の紹介 - C# 印刷ライブラリ
IronPrint は、精度、使いやすさ、速度を重視した、強力で展開可能な印刷ライブラリとして際立っています。 クロスプラットフォームのサポートとさまざまなドキュメント形式との互換性により、アプリケーションで効率的な印刷ソリューションを求める .NET 開発者にとって貴重なツールとなります。

主要機能
ここに、C#アプリケーションで物理的なドキュメントを印刷する際にIronPrintが際立つための重要な機能がいくつかあります:
1. クロスプラットフォームの互換性
- .NET バージョンのサポート: .NET 8、7、6、5、および Core 3.1+
- オペレーティング システム: Windows (7+、Server 2016+)、macOS (10+)、iOS (11+)、Android API 21+ (v5 "Lollipop")
- プロジェクトの種類: モバイル (Xamarin、MAUI、Avalonia)、デスクトップ (WPF、MAUI、Windows Avalonia)、コンソール (アプリとライブラリ)
2. サポートされている形式
- PDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE、BITMAP など、さまざまなドキュメント形式を処理します。
- ドキュメントの要件に応じて印刷設定をカスタマイズします。
3. 簡単なインストール
NuGet パッケージ マネージャー コンソールを使用してIronPrintライブラリをインストールします。
Install-Package IronPrint
あるいは、Visual Studio を使用してプロジェクトにインストールすることもできます。 ソリューション エクスプローラーでプロジェクトを右クリックし、[ソリューションの NuGet パッケージ マネージャーの管理] をクリックします。 NuGet ブラウズタブで "IronPrint" を検索し、検索結果から最新のIronPrintパッケージを選択し、インストールボタンをクリックしてプロジェクトに追加します。
IronPrint による印刷: コード例
1. 文書を印刷する
IronPrintは単純な Print メソッド を使用して、ドキュメントの無音印刷を提供します。 物理プリンタが使用できない場合は、OS で指定されたデフォルトのプリンタを使用して印刷します。
using IronPrint;
class Program
{
static void Main()
{
// Print the document
Printer.Print("newDoc.pdf");
}
}
using IronPrint;
class Program
{
static void Main()
{
// Print the document
Printer.Print("newDoc.pdf");
}
}
Imports IronPrint
Friend Class Program
Shared Sub Main()
' Print the document
Printer.Print("newDoc.pdf")
End Sub
End Class
2. ダイアログ付きで印刷
また、印刷中の制御をより良くするための print ダイアログ を表示する専用メソッドも提供します。 ShowPrintDialogAsync メソッドは非同期的に印刷するためにも使用できます。
using IronPrint;
class Program
{
static void Main()
{
// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
}
}
using IronPrint;
class Program
{
static void Main()
{
// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
}
}
Imports IronPrint
Friend Class Program
Shared Sub Main()
' Show print dialog
Printer.ShowPrintDialog("newDoc.pdf")
End Sub
End Class
3. 印刷設定をカスタマイズする
IronPrintは、ドキュメントの印刷をきめ細かく制御できるさまざまな print 設定 を提供します。
using IronPrint;
class Program
{
static void Main()
{
// Configure print settings
PrintSettings printSettings = new PrintSettings()
{
Dpi = 150,
NumberOfCopies = 2,
PaperOrientation = PaperOrientation.Portrait
};
// Print the document
Printer.Print("newDoc.pdf", printSettings);
}
}
using IronPrint;
class Program
{
static void Main()
{
// Configure print settings
PrintSettings printSettings = new PrintSettings()
{
Dpi = 150,
NumberOfCopies = 2,
PaperOrientation = PaperOrientation.Portrait
};
// Print the document
Printer.Print("newDoc.pdf", printSettings);
}
}
Imports IronPrint
Friend Class Program
Shared Sub Main()
' Configure print settings
Dim printSettings As New PrintSettings() With {
.Dpi = 150,
.NumberOfCopies = 2,
.PaperOrientation = PaperOrientation.Portrait
}
' Print the document
Printer.Print("newDoc.pdf", printSettings)
End Sub
End Class
使用されるクラスとメソッドをより深く理解するには、 API リファレンスページをご覧ください。
結論
C# でリストを印刷するには、データの複雑さと目的の出力に基づいて適切な方法を選択する必要があります。 シンプルなループ、String.Join()、LINQ、またはカスタムオブジェクトのために ToString() メソッドをカスタマイズするかにかかわらず、これらのアプローチを理解することで、C# アプリケーション内でリストの内容を効果的に表示できるようになります。 これらのテクニックを試してみて、特定のユースケースに最適なものを選択してください。
正確性、使いやすさ、スピードを求めるなら、 IronPrint が最適な印刷ライブラリです。 Web アプリを構築する場合でも、MAUI、Avalonia を操作する場合でも、.NET 関連のあらゆる作業を行う場合でも、IronPrint が役立ちます。 IronPrint の詳細については、このドキュメント ページをご覧ください。
IronPrint は有料ライブラリですが、無料トライアルもご利用いただけます。 ここからライブラリをダウンロードして試してみてください。
よくある質問
C# でリストを印刷するにはどうすればいいですか?
C# でリストを印刷するために IronPrint を使用することができます。 foreach または for ループを使用してリスト要素を反復処理し、フォーマットされた出力を IronPrint に渡して印刷します。
C# で動的配列を使用する利点は何ですか?
C# の動的配列、またはリストは、サイズが増減できるため柔軟性を提供します。それらは System.Collections.Generic 名前空間の一部であり、コレクションの効率的な処理と操作を可能にします。
C# でリストを逆順に印刷するにはどうすればいいですか?
リストを逆順に印刷するには、Reverse メソッドまたは LINQ の OrderByDescending を使用し、逆順にしたリストを IronPrint で印刷することができます。
印刷用にリストを文字列としてフォーマットするにはどうすればいいですか?
String.Join メソッドを使用して、リスト要素を指定されたセパレータで連結し、単一のフォーマットされた文字列にすることができます。このフォーマットされた文字列を IronPrint を使用して印刷できます。
カスタムオブジェクトの印刷における ToString メソッドの役割は何ですか?
ToString メソッドをオーバーライドすることで、カスタムオブジェクトのインスタンスが文字列としてどのように表現されるかを定義でき、IronPrint で印刷されたときの読みやすさが向上します。
C# で特定の要素をフィルタリングして印刷するにはどうすればいいですか?
LINQ メソッドの Where を使用して、リストから特定の要素をフィルタリングして選択できます。フィルタリングされた結果を IronPrint を使用して印刷できます。
.NET 向けの印刷ライブラリをインストールするにはどうすればいいですか?
NuGet Package Manager Console を使用してコマンド Install-Package IronPrint を入力するか、Visual Studio の NuGet Package Manager を通じて IronPrint をインストールできます。
.NET 開発者向けに IronPrint が提供する機能は何ですか?
IronPrint はクロスプラットフォーム互換性、さまざまなドキュメント形式のサポート、サイレント印刷、印刷ダイアログ、およびカスタマイズ可能な印刷設定を提供し、.NET 開発者にとって強力な選択肢です。




