.NET ヘルプ

C# コレクション (開発者に向けた使い方)

イントロダクション

C#は、多くの利用可能なプログラミング言語の中で、開発者にとって人気があり、適応性の高い選択肢となっています。 コレクションの概念は、C#の広範なライブラリとフレームワークの中心にあり、これは言語の主な利点の一つです。 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#コレクションタイプ

List

要素の迅速で簡単な挿入と削除を可能にする動的配列が、List クラスです。 柔軟なオプションであり、フィルタリング、検索、およびコンポーネントの操作を行う方法を提供するため、サイズ変更可能なコレクションが必要な状況に適しています。

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // adds element '6' to the end
numbers.Remove(3); // removes all the items that are '3'
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // adds element '6' to the end
numbers.Remove(3); // removes all the items that are '3'
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 all the items that are '3'
$vbLabelText   $csharpLabel

2. Dictionary<TKey, TValue> (ディクショナリ<TKey, TValue>)

高速な検索速度を持ち、一連のキーと値のペアはDictionary<TKey, TValue>クラスで表されます。 データに素早くアクセスすることが重要な状況で頻繁に使用されます。 このキーは、辞書内の要素にアクセスするために使用されます。

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
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
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 クラスによって実装されています。 それらはアプリケーションのニーズに基づいて、特定の順序で項目を管理するために使用することができます。

Queue<string> tasks = new Queue<string>(); // creating a queue class
tasks.Enqueue("Task 1"); // adding to the queue
tasks.Enqueue("Task 2");
Stack<double> numbers = new Stack<double>(); // creating a stack class
numbers.Push(3.14); // adding to the stack
numbers.Push(2.71);
Queue<string> tasks = new Queue<string>(); // creating a queue class
tasks.Enqueue("Task 1"); // adding to the queue
tasks.Enqueue("Task 2");
Stack<double> numbers = new Stack<double>(); // creating a stack class
numbers.Push(3.14); // adding to the stack
numbers.Push(2.71);
Dim tasks As New Queue(Of String)() ' creating a queue class
tasks.Enqueue("Task 1") ' adding to the queue
tasks.Enqueue("Task 2")
Dim numbers As New Stack(Of Double)() ' creating a stack class
numbers.Push(3.14) ' adding to the stack
numbers.Push(2.71)
$vbLabelText   $csharpLabel

HashSet

一意のアイテムが順不同のコレクションに配置されている場合、HashSet クラスによって表されます。 それは、差、和集合、交差といった集合操作を効果的に実行する方法を提供します。

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
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
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

C# コレクション (開発者向けの仕組み): 図 1 - IronPDF ウェブサイトページ

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文書を扱う場合でも、ライブラリは効率的なPDFの作成とレンダリングを提供するように設計されています。

    IronPDFのドキュメントについて詳しく知るには、IronPDF Documentationを参照してください。

IronPDFのインストール

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

Install-Package IronPdf

C# コレクション (開発者向けの仕組み): 図 2 - Package Manager Consoleを使用したIronPDFのインストール

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

C# コレクション(開発者のための機能):図 3 - NuGet パッケージマネージャーでの IronPDF のインストール

IronPDFを使用したコレクションによるドキュメント作成

IronPDFのインターフェースに入る前に、データ構造と組織におけるコレクションの役割を理解することが重要です。 開発者は、コレクションを使用することによって、物のグループを体系的に保存、取得、および変更することができます。 List、Dictionary<TKey, TValue>、HashSetなど、多くの異なるタイプが利用可能であるため、開発者は自分の要件に最も適したコレクションを選択できます。

販売取引のリストを含むレポートを作成する必要があると想像してください。 データは、追加の処理と表示の基盤として機能するListを使用して効果的に整理することができます。

public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
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
};
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
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
};
Public Class Transaction
	Public Property ProductName() As String
	Public Property Amount() As Decimal
	Public Property [Date]() As DateTime
End Class
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内で、各製品名、取引額、取引日時を一覧表示する簡単な表を作成します。

var pdfDocument = new IronPdf.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);
pdf.SaveAs(pdfFilePath);
var pdfDocument = new IronPdf.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);
pdf.SaveAs(pdfFilePath);
Dim pdfDocument = New IronPdf.HtmlToPdf()
' HTML content with a table populated by data from the 'transactions' list
Dim 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)
pdf.SaveAs(pdfFilePath)
$vbLabelText   $csharpLabel

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

C#コレクション(開発者向け):図4 - 前のコードから出力されたPDF

上記の画面は、上記のコードから生成された出力を示しています。 コードの詳細については、HTMLを使用してPDFを作成する例をご参照ください。

結論

IronPdfとコレクションを組み合わせることで、ダイナミックなドキュメント制作が可能になります。 開発者はコレクションを利用してデータを効果的に管理および整理でき、IronPDF を使用することで視覚的に美しい PDF ドキュメントを簡単に作成できます。 IronPDF とコレクションの連携による強力なソリューションは、C# アプリケーションにおける動的コンテンツ生成に対して信頼性と適応性を提供します。請求書、レポート、その他どのような種類のドキュメントを生成する場合でも対応可能です。

IronPDF の $749 Lite エディションには、1 年間のソフトウェアサポート、アップグレードオプション、および永久ライセンスが含まれています。 ユーザーは、透かし入りの試用期間中に実際の状況で製品を評価する機会も得られます。 IronPDF の費用、ライセンス、および無料トライアルについて詳しく知るには、IronPDF のライセンス情報をご覧ください。 詳細については、Iron Softwareのウェブサイトをご覧ください。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
MSTest C# (開発者向けの動作説明)
次へ >
C# Null 条件演算子(開発者向けの動作説明)