フッターコンテンツにスキップ
.NETヘルプ

C# Collection(開発者向けの動作方法)

C#は、多くの利用可能なプログラミング言語の中で、開発者にとって人気があり柔軟な選択肢となっています。 コレクションの概念は、C#の豊富なライブラリとフレームワークの核心にあり、これは言語の主な利点の1つです。 C#では、コレクションはデータを効果的に格納し整理するために不可欠です。 それらは開発者に、多様なプログラミング問題を解決するための幅広い効果的なツールを提供します。 この記事では、コレクションの機能、種類、および最適な使用戦略についてさらに掘り下げていきます。

C#のコレクションの使い方

  1. 新しいコンソールアプリプロジェクトを作成します。
  2. C#でコレクション用のオブジェクトを作成します。
  3. オブジェクトのセットを複数格納できるコレクションクラスに値を追加します。
  4. 追加、削除、ソートなどの値操作を行います。
  5. 結果を表示し、オブジェクトを破棄します。

C#: コレクションの理解

C#のコレクションは、プログラマがオブジェクトクラスのセットを操作し格納するためのコンテナです。 これらのオブジェクトは柔軟で多くのプログラミング環境に適応し、同種または異種のものの場合があります。 ほとんどのコレクションクラスは、C#のSystem名前空間の構成要素を実装しており、System.CollectionsやSystem.Collections.Genericなどの名前空間のインポートを意味します。これにより、ジェネリックおよび非ジェネリックなさまざまなコレクションクラスが提供されます。 コレクションにより、動的メモリ割り当て、追加、検索、およびコレクションクラス内のアイテムのソートが可能になります。

非ジェネリックコレクションタイプ

ArrayList、Hashtable、Queueは、C#の初期のバージョンに含まれる非ジェネリックコレクションクラスです。 これらのコレクションは、保存および操作したいもののタイプを明示的に定義する代替手段を提供します。 ただし、開発者は通常、その優れたパフォーマンスと型の安全性のためにジェネリックコレクションを選択します。

ジェネリックコレクション

C#の後続のバージョンでは、非ジェネリックコレクションの欠点を克服するためにジェネリックコレクションが含まれています。 これにより、コンパイル時の型の安全性が提供され、開発者が厳密に型指定されたデータを扱うことができます。 一般的に使用されるジェネリックコレクションクラスには、List、Dictionary<TKey, TValue>、Queue、Stackなどがあります。 これらのコレクションは、優れたパフォーマンスとコンパイル時の型検証を提供するため、現代のC#開発において最適な選択肢となっています。

主要なC#コレクションタイプ

1. List

動的配列であり、要素の迅速で簡単な挿入と削除を容易にするのがListクラスです。 フィルタリング、検索、要素の操作を行うための方法を提供するため、リサイズ可能なコレクションを必要とする状況において柔軟な選択肢です。

// Creating a list with integers and adding/removing elements
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // Adds element '6' to the end
numbers.Remove(3); // Removes the first occurrence of the element '3'
// Creating a list with integers and adding/removing elements
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // Adds element '6' to the end
numbers.Remove(3); // Removes the first occurrence of the element '3'
' Creating a list with integers and adding/removing elements
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
numbers.Add(6) ' Adds element '6' to the end
numbers.Remove(3) ' Removes the first occurrence of the element '3'
$vbLabelText   $csharpLabel

2. Dictionary<TKey, TValue>

高速な検索速度を持つキーと値のペアのコレクションはDictionary<TKey, TValue>クラスによって表されます。 一意のキー値を介してデータに迅速にアクセスすることが重要な状況で頻繁に使用されます。 このキーは、辞書内の要素にアクセスするために使用されます。

// Creating a dictionary mapping names to ages
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap.Add("John", 25); // The string "John" is the key that can access the value 25
ageMap["Jane"] = 30; // Setting the key "Jane" to hold the value 30
// Creating a dictionary mapping names to ages
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap.Add("John", 25); // The string "John" is the key that can access the value 25
ageMap["Jane"] = 30; // Setting the key "Jane" to hold the value 30
' Creating a dictionary mapping names to ages
Dim ageMap As New Dictionary(Of String, Integer)()
ageMap.Add("John", 25) ' The string "John" is the key that can access the value 25
ageMap("Jane") = 30 ' Setting the key "Jane" to hold the value 30
$vbLabelText   $csharpLabel

3. QueueおよびStack

先入れ先出し(FIFO)コレクションと後入れ先出し(LIFO)コレクションのパラダイムは、それぞれジェネリックQueueおよびジェネリックStackクラスによって実装されています。 アプリケーションのニーズに基づいて、特定の順序でアイテムを管理するために使用できます。

// Creating and manipulating a queue
Queue<string> tasks = new Queue<string>(); 
tasks.Enqueue("Task 1"); // Adding to the queue
tasks.Enqueue("Task 2");

// Creating and manipulating a stack
Stack<double> numbers = new Stack<double>();
numbers.Push(3.14); // Adding to the stack
numbers.Push(2.71);
// Creating and manipulating a queue
Queue<string> tasks = new Queue<string>(); 
tasks.Enqueue("Task 1"); // Adding to the queue
tasks.Enqueue("Task 2");

// Creating and manipulating a stack
Stack<double> numbers = new Stack<double>();
numbers.Push(3.14); // Adding to the stack
numbers.Push(2.71);
' Creating and manipulating a queue
Dim tasks As New Queue(Of String)()
tasks.Enqueue("Task 1") ' Adding to the queue
tasks.Enqueue("Task 2")

' Creating and manipulating a stack
Dim numbers As New Stack(Of Double)()
numbers.Push(3.14) ' Adding to the stack
numbers.Push(2.71)
$vbLabelText   $csharpLabel

4. HashSet

ユニークなアイテムが無秩序なコレクションで整理されているのは、HashSetクラスによって表されます。 差異、和、交差などのセット操作を実行するための効果的な方法を提供します。

// Creating hashsets and performing a union operation
HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 };
HashSet<int> unionSet = new HashSet<int>(setA);
unionSet.UnionWith(setB); // Combining setA and setB
// Creating hashsets and performing a union operation
HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 };
HashSet<int> unionSet = new HashSet<int>(setA);
unionSet.UnionWith(setB); // Combining setA and setB
' Creating hashsets and performing a union operation
Dim setA As New HashSet(Of Integer) From {1, 2, 3, 4}
Dim setB As New HashSet(Of Integer) From {3, 4, 5, 6}
Dim unionSet As New HashSet(Of Integer)(setA)
unionSet.UnionWith(setB) ' Combining setA and setB
$vbLabelText   $csharpLabel

IronPDF

<!a href="/static-assets/pdf/blog/csharp-collection/csharp-collection-1.webp">C# Collection (How It Works For Developers): Figure 1 - IronPDF website page

C#のライブラリであるIronPDFは、.NETアプリケーションでPDFドキュメントを作成、編集、表示するのを簡単にします。 多くのライセンスオプション、クロスプラットフォームの互換性、高品質なレンダリング、HTMLからPDFへの変換を提供します。 IronPDFの使いやすいAPIはPDFの取り扱いを簡単にし、C#開発者にとって貴重なツールです。

IronPDFの際立った機能は、すべてのレイアウトとスタイルを保持するHTMLからPDFへの変換機能です。 ウェブコンテンツからPDFを生成するため、レポート、請求書、ドキュメントに最適です。 HTMLファイル、URL、およびHTML文字列を簡単にPDFに変換できます。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronPDFの主な機能には以下が含まれます:

  • HTMLからPDFへの変換: IronPDFを使用すると、CSSやJavaScriptを含むHTMLテキストからPDFドキュメントを作成できます。 これは、ウェブ開発ツールに精通しており、HTMLとCSSを使用してPDFを作成したい人に特に有用です。
  • PDFの生成と操作: ライブラリは、プログラムでPDFドキュメントを作成する機能を提供します。 さらに、テキスト抽出、ウォーターマークの追加、PDFの分割など、既存のPDFを編集する機能を提供します。
  • 優れたレンダリング: IronPDFはレンダリングエンジンを使用して、最も高品質なPDF出力を生成し、最終ドキュメントが明瞭さと視覚的整合性を保持することを保証します。
  • クロスプラットフォームの互換性: IronPDFは.NET Coreと.NET Frameworkの両方で動作するように設計されており、さまざまなアプリケーションや多様なプラットフォームで使用可能です。
  • パフォーマンス最適化: 大規模または複雑なPDFドキュメントを取り扱う際でも、ライブラリは効率的なPDF生成とレンダリングを提供するよう設計されています。

IronPDFのドキュメントについて詳しく知りたい場合は、IronPDFドキュメントをご参照ください。

IronPDFのインストール

まず、パッケージマネージャーコンソールまたはNuGetパッケージマネージャーを使用して、IronPDFライブラリをインストールします:

Install-Package IronPdf

<!a href="/static-assets/pdf/blog/csharp-collection/csharp-collection-2.webp">C# Collection (How It Works For Developers): Figure 2 - Installing IronPDF with the Package Manager Console

NuGetパッケージマネージャーを使用して"IronPDF"パッケージを検索するのも別の選択肢です。 このリストから、IronPDFに関連するすべてのNuGetパッケージの中から必要なパッケージを選択してダウンロードできます。

<!a href="/static-assets/pdf/blog/csharp-collection/csharp-collection-3.webp">C# Collection (How It Works For Developers): Figure 3 - Installing IronPDF with the NuGet Package Manager

IronPDFを使用したコレクションでのドキュメント作成

IronPDFとのインターフェースに入る前に、データ構造と組織においてコレクションが果たす役割を理解することが重要です。 開発者は、コレクションを使用して、グループ化されたオブジェクトを整理して格納し、取り出し、変更することができます。 List、Dictionary<TKey, TValue>、HashSetなど、利用可能なさまざまなタイプの中から、開発者は自分の要求に最も適したコレクションを選ぶことができます。

たとえば、販売取引のリストを含む報告書を作成しなければならないと想像してください。 データは、追加処理および表示の基礎として、Listを使用して効果的に整理できます。

// Define the Transaction class
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}

// Create a list of transactions
List<Transaction> transactions = new List<Transaction>
{
    new Transaction { ProductName = "Product A", Amount = 100.50m, Date = DateTime.Now.AddDays(-2) },
    new Transaction { ProductName = "Product B", Amount = 75.20m, Date = DateTime.Now.AddDays(-1) },
    // Add more transactions as needed
};
// Define the Transaction class
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}

// Create a list of transactions
List<Transaction> transactions = new List<Transaction>
{
    new Transaction { ProductName = "Product A", Amount = 100.50m, Date = DateTime.Now.AddDays(-2) },
    new Transaction { ProductName = "Product B", Amount = 75.20m, Date = DateTime.Now.AddDays(-1) },
    // Add more transactions as needed
};
' Define the Transaction class
Public Class Transaction
	Public Property ProductName() As String
	Public Property Amount() As Decimal
	Public Property [Date]() As DateTime
End Class

' Create a list of transactions
Private transactions As New List(Of Transaction) From {
	New Transaction With {
		.ProductName = "Product A",
		.Amount = 100.50D,
		.Date = DateTime.Now.AddDays(-2)
	},
	New Transaction With {
		.ProductName = "Product B",
		.Amount = 75.20D,
		.Date = DateTime.Now.AddDays(-1)
	}
}
$vbLabelText   $csharpLabel

PDF内では、各製品名、取引金額、および日付を一覧にしたシンプルなテーブルを作成します。

using IronPdf;

// Create a PDF document renderer
var pdfDocument = new HtmlToPdf();

// HTML content with a table populated by data from the 'transactions' list
string htmlContent = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>";
foreach (var transaction in transactions)
{
    htmlContent += $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>";
}
htmlContent += "</table>";

// Convert HTML to PDF
PdfDocument pdf = pdfDocument.RenderHtmlAsPdf(htmlContent);

// Specify the file path to save the PDF
string pdfFilePath = "transactions_report.pdf";
pdf.SaveAs(pdfFilePath);
using IronPdf;

// Create a PDF document renderer
var pdfDocument = new HtmlToPdf();

// HTML content with a table populated by data from the 'transactions' list
string htmlContent = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>";
foreach (var transaction in transactions)
{
    htmlContent += $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>";
}
htmlContent += "</table>";

// Convert HTML to PDF
PdfDocument pdf = pdfDocument.RenderHtmlAsPdf(htmlContent);

// Specify the file path to save the PDF
string pdfFilePath = "transactions_report.pdf";
pdf.SaveAs(pdfFilePath);
Imports IronPdf

' Create a PDF document renderer
Private pdfDocument = New HtmlToPdf()

' HTML content with a table populated by data from the 'transactions' list
Private htmlContent As String = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>"
For Each transaction In transactions
	htmlContent &= $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>"
Next transaction
htmlContent &= "</table>"

' Convert HTML to PDF
Dim pdf As PdfDocument = pdfDocument.RenderHtmlAsPdf(htmlContent)

' Specify the file path to save the PDF
Dim pdfFilePath As String = "transactions_report.pdf"
pdf.SaveAs(pdfFilePath)
$vbLabelText   $csharpLabel

一度生成されたPDFドキュメントは、開発者はそれをディスクに保存したり、ユーザーに表示したりすることができます。 IronPDFは、ブラウザストリーミング、ファイル保存、クラウドストレージ統合など、いくつかの出力オプションを提供します。

<!a href="/static-assets/pdf/blog/csharp-collection/csharp-collection-4.webp">C# Collection (How It Works For Developers): Figure 4 - Outputted PDF from the previous code

プログラムで生成された上記のコードに基づいて出力されたPDFです。 コードについて詳しく知りたい場合は、Using HTML to Create a PDF Exampleを参照してください。

結論

コレクションとIronPDFを組み合わせることで、動的ドキュメント生成の幅広い機会が可能になります。 開発者はコレクションを利用してデータを効果的に管理および整理でき、IronPDFは視覚的に美しいPDFドキュメントを作成することを簡単にします。 IronPDFとコレクションの組み合わせた力は、C#アプリケーションでの動的コンテンツ生成に対する信頼性と柔軟性のあるソリューションを提供し、どのような種類のドキュメントを作成している場合でも、請求書、報告書、その他のドキュメントでも対応します。

IronPDFの$799ライト版には、1年間のソフトウェアサポート、アップグレードオプション、および恒久的なライセンスが含まれます。 また、ユーザーは、ウォーターマーク付きの試用期間中に製品を実際の状況で評価する機会を得ます。 IronPDFのコスト、ライセンス、および無料試用について詳しく知りたい場合は、IronPDFライセンス情報をご覧ください。 Iron Softwareに関する詳細情報は、Iron Software Websiteをご参照ください。

よくある質問

C# のコレクションとは何であり、なぜ重要なのですか?

C# のコレクションは、データの保存と整理に不可欠であり、複雑なプログラミングチャレンジを効率的に処理するためのツールを開発者に提供します。これらは動的メモリ割り当てとデータセットの容易な操作を可能にします。

C# の非ジェネリックコレクションとジェネリックコレクションの違いは何ですか?

非ジェネリックコレクションは、ArrayListHashtable など、型の安全性が低く、任意のオブジェクトタイプを格納できます。ジェネリックコレクションは、ListDictionary など型の安全性を提供し、データ型の一貫性を強制することで、パフォーマンスを向上させます。

C# でジェネリックリストを作成するにはどうすればよいですか?

C# でジェネリックリストは、List クラスを使用して作成できます。例えば、整数のリストは List numbers = new List { 1, 2, 3 }; で作成できます。

C# で HTML を PDF に変換するにはどうすればいいですか?

IronPDF の RenderHtmlAsPdf メソッドを使用して HTML 文字列を PDF に変換することができます。また、HTML ファイルや URL を PDF ドキュメントに変換し、レイアウトやスタイリングの一貫性を維持することもサポートしています。

C# でコレクションを使用するためのベストプラクティスは何ですか?

C# でのコレクション使用のベストプラクティスには、ニーズに合った型のコレクションを選択することが含まれます。Dictionary をキーと値のペア用に使用し、List を順序付きリスト用に使用し、不要になったときにコレクションを破棄して適切なメモリ管理を確保します。

コレクションは、C# アプリケーションでの PDF 作成をどのように強化できますか?

コレクションはドキュメント作成のためにデータを効率的に整理できます。例えば、List を使用して販売データを集めることで、IronPDF を使用した包括的な PDF レポートの生成を容易にし、データ管理とプレゼンテーションを効率化します。

IronPDFのライセンスオプションはどのようになっていますか?

IronPDF はライセンスとして 1 年間のサポートとアップグレードを含む Lite ライセンスと、評価のための透かし付き試用版を提供しています。これらのオプションにより、開発者は IronPDF の機能を自社プロジェクトでテストおよび実装できます。

.NETプロジェクトにIronPDFをインストールするにはどうすれば良いですか?

.NET プロジェクトに IronPDF をインストールするには、Install-Package IronPdf コマンドを使用して NuGet パッケージマネージャーを使用できます。あるいは、NuGet パッケージマネージャー内で 'IronPDF' を検索してプロジェクトに追加することも可能です。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。