.NET ヘルプ

C# リンクドリスト (開発者向けの仕組み)

リンクリストは、一連のノードで構成される線形データ構造で、要素とも呼ばれます。 配列では要素/ノードが連続したメモリ位置に保存されますが、リンクリストでは動的メモリ割り当てを利用するため、要素/ノードはメモリ全体に散在することができます。

最も単純な形では、「リンクリスト」は線形にリンクされたノードで構成されます。 各ノードは2つの主要部分を含みます:

  1. データ: ノードに格納されたペイロード。 これは実装によって任意のデータ型である可能性があります。例えば整数、文字列、オブジェクトなどです。

  2. 次のポインタ: シーケンス内の次のノードへの参照(またはポインタ)。 このポインタは、リンクリスト内で次のノードのメモリ位置を指し示します。

    リンクリストの最後のノードは通常、ヌル参照を指し、リストの終わりを示します。

    この記事では、C#のリンクリストを詳細に見ていき、IronPDFライブラリIron SoftwareからのPDF生成ツールも探ります。

連結リストの種類

単方向リスト

単一リンクリストは、通常、シーケンス内の次のノードを指す、1つの参照のみを持つノードを持ちます。 リストのトラバースは通常、ヘッド(最初のノード)からテール(最後のノード)への一方向の移動に限定されます。

ダブリリンクリスト

二重リンクリストでは、各ノードに2つの参照が含まれています。一つは次のノードを指し、もう一つはシーケンス内の前のノードを指します。 この双方向リンクは、前方向および後方向の両方でのトラバーサルを可能にします。

循環リンクリスト

循環連結リストでは、最後のノードが最初のノードに指し戻され、円形の構造を形成します。 この種類のリンクリストは、単方向または双方向リンクノードを使用して実装することができます。

リンクドリストの基本操作

  1. 挿入: リストに新しいノードを特定の位置で追加すること。例えば、リストの先頭、末尾、または中間。

  2. 削除: 指定されたオブジェクトノードをリストから削除し、隣接するノードのポインタを適切に調整します。

  3. トラバーサル:リストを反復処理して、各ノードのデータにアクセスしたり操作したりすること。

  4. 検索: データで指定された値に基づいてリスト内の特定のノードを見つけること。

C#のリンクリスト;

C#では、System.Collections.Generic名前空間のLinkedListクラスを使用して連結リストを実装できます。 以下に基本的な操作の全例を示します:

namespace CsharpSamples
{
public class Program
{
    public static void Main()
        {
            // Create a new linked list of integers
            LinkedList<int> linkedList = new LinkedList<int>();
            // Add elements to the linked list which create objects from node class
            linkedList.AddLast(10);
            linkedList.AddLast(20);
            linkedList.AddLast(30);
            linkedList.AddLast(40);
            // Traverse and Print the elements of the linked list
            Console.WriteLine("Traverse Linked List elements:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"Number of Linked List elements:{linkedList.Count}"); // use count property to display length
            // Find/Search Element in Linked List
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);// method returns the node
            Console.WriteLine($"Found Value:{foundNode.Value}, Next Element:{foundNode.Next.Value}, Previous Element:{foundNode.Previous.Value}"); // prints next node, previous node
            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            linkedList.AddAfter(current, 25);
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
            Console.WriteLine("\nLinked List elements after insertion:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            // Remove an existing node from the linked list 
            linkedList.Remove(30); // remove current node
            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
        }
    }
}
namespace CsharpSamples
{
public class Program
{
    public static void Main()
        {
            // Create a new linked list of integers
            LinkedList<int> linkedList = new LinkedList<int>();
            // Add elements to the linked list which create objects from node class
            linkedList.AddLast(10);
            linkedList.AddLast(20);
            linkedList.AddLast(30);
            linkedList.AddLast(40);
            // Traverse and Print the elements of the linked list
            Console.WriteLine("Traverse Linked List elements:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"Number of Linked List elements:{linkedList.Count}"); // use count property to display length
            // Find/Search Element in Linked List
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);// method returns the node
            Console.WriteLine($"Found Value:{foundNode.Value}, Next Element:{foundNode.Next.Value}, Previous Element:{foundNode.Previous.Value}"); // prints next node, previous node
            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            linkedList.AddAfter(current, 25);
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
            Console.WriteLine("\nLinked List elements after insertion:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            // Remove an existing node from the linked list 
            linkedList.Remove(30); // remove current node
            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
        }
    }
}
Imports Microsoft.VisualBasic

Namespace CsharpSamples
Public Class Program
	Public Shared Sub Main()
			' Create a new linked list of integers
			Dim linkedList As New LinkedList(Of Integer)()
			' Add elements to the linked list which create objects from node class
			linkedList.AddLast(10)
			linkedList.AddLast(20)
			linkedList.AddLast(30)
			linkedList.AddLast(40)
			' Traverse and Print the elements of the linked list
			Console.WriteLine("Traverse Linked List elements:")
			For Each item In linkedList
				Console.WriteLine(item)
			Next item
			Console.WriteLine($"Number of Linked List elements:{linkedList.Count}") ' use count property to display length
			' Find/Search Element in Linked List
			Console.WriteLine(vbLf & "Find/Search Element Linked List elements: 30")
			Dim foundNode = linkedList.Find(30) ' method returns the node
			Console.WriteLine($"Found Value:{foundNode.Value}, Next Element:{foundNode.Next.Value}, Previous Element:{foundNode.Previous.Value}") ' prints next node, previous node
			' Insert an element at a specified node
			Dim current As LinkedListNode(Of Integer) = linkedList.Find(20)
			linkedList.AddAfter(current, 25)
			Console.WriteLine($vbLf & "Number of Linked List elements:{linkedList.Count}") ' use count property to display length
			Console.WriteLine(vbLf & "Linked List elements after insertion:")
			For Each item In linkedList
				Console.WriteLine(item)
			Next item
			' Remove an existing node from the linked list 
			linkedList.Remove(30) ' remove current node
			Console.WriteLine(vbLf & "Linked List elements after removal:")
			For Each item In linkedList
				Console.WriteLine(item)
			Next item
			Console.WriteLine($vbLf & "Number of Linked List elements:{linkedList.Count}") ' use count property to display length
	End Sub
End Class
End Namespace
$vbLabelText   $csharpLabel

コードの説明

  1. 新しいLinkedList&lt;int&gt;()を使用して新しい整数のリンクリストを作成します。

  2. リンクリストに指定された値オブジェクトを追加します。

  3. foreachループを使用して、リンクリストの要素をトラバースして出力します。

  4. リンクリストの要素を検索する。

  5. Find メソッドと AddAfter メソッドを使用して、指定されたノードに要素を挿入します。

  6. Remove メソッドを使用して、リンクリストから既存のノードを削除します。

出力

C# リンクリスト(開発者向けの仕組み):図 1 - リンクリストの出力

IronPDFの紹介

IronPDF についてもっと知る は、Iron Software によって開発および管理されている強力な C# PDF ライブラリです。 それは、.NETプロジェクト内でPDFドキュメントを作成、編集、およびコンテンツを抽出するための包括的な機能セットを提供します。

IronPDFのキーポイント

HTMLをPDFに変換

IronPDFは、HTMLコンテンツをPDF形式に変換することができます。 HTMLページ、URL、およびHTML文字列を簡単にPDFに変換できます。

リッチAPI

このライブラリは、開発者がHTMLから直接プロフェッショナル品質のPDFを生成できるユーザーフレンドリーなAPIを提供します。 請求書、レポート、その他のドキュメントの作成が必要な場合、IronPDFはプロセスを簡素化します。

クロスプラットフォームサポート

IronPDFは、.NET Core、.NET Standard、および.NET Frameworkを含むさまざまな.NET環境に対応しています。 それは、Windows、Linux、およびmacOSプラットフォームで動作します。

多様性

IronPDFは、さまざまなプロジェクトタイプをサポートしており、Webアプリケーション(BlazorとWebForms)、デスクトップアプリケーション(WPFとMAUI)、コンソールアプリケーションなどがあります。

コンテンツソース

さまざまなコンテンツソース、例えばHTMLファイル、Razorビュー(Blazorサーバー)、CSHTML(MVCおよびRazor)、ASPX(WebForms)、XAML(MAUI)からPDFを生成できます。

追加機能

  1. PDFにヘッダーとフッターを追加。

  2. PDFページを結合、分割、追加、コピー、削除します。

  3. パスワード、権限、デジタル署名を設定します。

  4. マルチスレッドおよび非同期サポートによりパフォーマンスを最適化します。

互換性

IronPDFはPDF標準に準拠しており、バージョン1.2から1.7、PDF/UA、およびPDF/Aを含みます。 また、UTF-8文字エンコーディング、ベースURL、およびアセットエンコーディングもサポートしています。

LinkedListを使用してPDFドキュメントを生成する

次に、IronPDFを使用してPDFドキュメントを作成し、LinkedList文字列の使用方法も示します。

まずは、Visual Studioを開き、以下のようにプロジェクトテンプレートからコンソールアプリケーションを作成します。

C# リンクリスト(開発者向けの仕組み):図2 - 新しいプロジェクト

プロジェクト名と場所を指定してください。

C# リンクドリスト(開発者向けの仕組み):図 3 - プロジェクト構成

必要な .NET バージョンを選択してください。

C# リンクリスト (開発者向けの仕組み): 図 4 - ターゲットフレームワーク

以下のようにVisual StudioパッケージマネージャーからIronPDFをインストールします。

C# リンクリスト(開発者向けの動作方法):図5 - IronPDFのインストール

また、以下のコマンドラインを使ってインストールすることもできます。

dotnet add package IronPdf --version 2024.4.2
dotnet add package IronPdf --version 2024.4.2
SHELL

以下のコードを追加してください。

using CsharpSamples;
public class Program
{
    public static void Main()
    {
            var content = "<h1>Demonstrate IronPDF with C# LinkedList</h1>";
            content += "<h2>Create a new linked list of strings</h2>";
            content += "<p></p>";
            content += "<p>Create a new linked list of strings with new LinkedList<string>()</p>";
            // Create a new linked list of strings
            LinkedList<string> linkedList = new LinkedList<string>();
            // Add elements to the linked list
            content += "<p>Add Apple to linkedList</p>";
            linkedList.AddLast("Apple");
            content += "<p>Add Banana to linkedList</p>";
            linkedList.AddLast("Banana");
            content += "<p>Add Orange to linkedList</p>";
            linkedList.AddLast("Orange");
            content += "<h2>Print the elements of the linked list</h2>";
            // Print the elements of the linked list
            Console.WriteLine("Linked List elements:");
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Insert an element at a specific position</h2>";
            // Insert an element at a specific position
            LinkedListNode<string> node = linkedList.Find("Banana");
            linkedList.AddAfter(node, "Mango");
            content += "<p>Find Banana and insert Mango After</p>";
            Console.WriteLine("\nLinked List elements after insertion:");
            content += "<h2>Linked List elements after insertion:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Remove an element from the linked list</h2>";
            // Remove an element from the linked list
            linkedList.Remove("Orange");
            content += "<p>Remove Orange from linked list</p>";
            Console.WriteLine("\nLinked List elements after removal:");
            content += "<h2>Linked List elements after removal:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            // create Renderer
            var renderer = new ChromePdfRenderer();
            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Save to a file or Stream
            pdf.SaveAs("AwesomeIronOutput.pdf");        
    }
}
using CsharpSamples;
public class Program
{
    public static void Main()
    {
            var content = "<h1>Demonstrate IronPDF with C# LinkedList</h1>";
            content += "<h2>Create a new linked list of strings</h2>";
            content += "<p></p>";
            content += "<p>Create a new linked list of strings with new LinkedList<string>()</p>";
            // Create a new linked list of strings
            LinkedList<string> linkedList = new LinkedList<string>();
            // Add elements to the linked list
            content += "<p>Add Apple to linkedList</p>";
            linkedList.AddLast("Apple");
            content += "<p>Add Banana to linkedList</p>";
            linkedList.AddLast("Banana");
            content += "<p>Add Orange to linkedList</p>";
            linkedList.AddLast("Orange");
            content += "<h2>Print the elements of the linked list</h2>";
            // Print the elements of the linked list
            Console.WriteLine("Linked List elements:");
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Insert an element at a specific position</h2>";
            // Insert an element at a specific position
            LinkedListNode<string> node = linkedList.Find("Banana");
            linkedList.AddAfter(node, "Mango");
            content += "<p>Find Banana and insert Mango After</p>";
            Console.WriteLine("\nLinked List elements after insertion:");
            content += "<h2>Linked List elements after insertion:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Remove an element from the linked list</h2>";
            // Remove an element from the linked list
            linkedList.Remove("Orange");
            content += "<p>Remove Orange from linked list</p>";
            Console.WriteLine("\nLinked List elements after removal:");
            content += "<h2>Linked List elements after removal:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            // create Renderer
            var renderer = new ChromePdfRenderer();
            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Save to a file or Stream
            pdf.SaveAs("AwesomeIronOutput.pdf");        
    }
}
Imports Microsoft.VisualBasic
Imports CsharpSamples
Public Class Program
	Public Shared Sub Main()
			Dim content = "<h1>Demonstrate IronPDF with C# LinkedList</h1>"
			content &= "<h2>Create a new linked list of strings</h2>"
			content &= "<p></p>"
			content &= "<p>Create a new linked list of strings with new LinkedList<string>()</p>"
			' Create a new linked list of strings
			Dim linkedList As New LinkedList(Of String)()
			' Add elements to the linked list
			content &= "<p>Add Apple to linkedList</p>"
			linkedList.AddLast("Apple")
			content &= "<p>Add Banana to linkedList</p>"
			linkedList.AddLast("Banana")
			content &= "<p>Add Orange to linkedList</p>"
			linkedList.AddLast("Orange")
			content &= "<h2>Print the elements of the linked list</h2>"
			' Print the elements of the linked list
			Console.WriteLine("Linked List elements:")
			For Each item In linkedList
				content &= $"<p>{item}</p>"
				Console.WriteLine(item)
			Next item
			content &= "<h2>Insert an element at a specific position</h2>"
			' Insert an element at a specific position
			Dim node As LinkedListNode(Of String) = linkedList.Find("Banana")
			linkedList.AddAfter(node, "Mango")
			content &= "<p>Find Banana and insert Mango After</p>"
			Console.WriteLine(vbLf & "Linked List elements after insertion:")
			content &= "<h2>Linked List elements after insertion:</h2>"
			For Each item In linkedList
				content &= $"<p>{item}</p>"
				Console.WriteLine(item)
			Next item
			content &= "<h2>Remove an element from the linked list</h2>"
			' Remove an element from the linked list
			linkedList.Remove("Orange")
			content &= "<p>Remove Orange from linked list</p>"
			Console.WriteLine(vbLf & "Linked List elements after removal:")
			content &= "<h2>Linked List elements after removal:</h2>"
			For Each item In linkedList
				content &= $"<p>{item}</p>"
				Console.WriteLine(item)
			Next item
			' create Renderer
			Dim renderer = New ChromePdfRenderer()
			' Create a PDF from HTML string
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			' Save to a file or Stream
			pdf.SaveAs("AwesomeIronOutput.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

コードの説明

  1. まず、コンテンツ文字列オブジェクトを使用してPDFのコンテンツを作成します。 コンテンツはHTML文字列として作成されています。

  2. 新しいLinkedList<string>()を使用して文字列の新しいリンクリストを作成します。

  3. リンクリストに要素を追加し、PDFコンテンツ文字列にも追加します。

  4. 連結リストの要素を印刷する。

  5. AddAfter メソッドを使用して特定の位置に要素を挿入し、結果のリストを表示します。

  6. Removeメソッドを使用してリンクリストから要素を削除し、結果のリストを表示してください。

  7. 最後に、ChromePdfRendererRenderHtmlAsPdf、およびSaveAsメソッドを使用して、生成されたHTMLコンテンツ文字列をPDFドキュメントに保存します。

出力

C# リンクトリスト(開発者向けの動作方法):図6 - IronPDF と `LinkedList` 出力

出力には透かしが入っていますが、IronPDFライセンスページから有効なライセンスを使用して削除できます。

IronPDFライセンス

IronPDFライブラリにはライセンスが必要です。ライセンスは製品ライセンスページから取得できます。

以下のappSettings.jsonファイルにキーを貼り付けてください。

{
  "IronPdf.License.LicenseKey" = "The Key Goes Here"
}

結論

C# LinkedList は、要素のコレクションを管理するための多用途のデータ構造を提供し、デフォルトのハッシュ関数に似た動的リサイズを可能にしつつ、効率的な挿入と削除を提供します。 リンクリストは、スタック、キュー、シンボルテーブル、およびメモリ管理システムの実装など、さまざまなアプリケーションやアルゴリズムで一般的に使用されます。 連結リストの特性と操作を理解することは、効率的でスケーラブルなソフトウェアソリューションを構築するために不可欠です。

要約すると、リンクリストは動的なデータ構造や頻繁な挿入/削除が発生するシナリオにおいて優れていますが、頻繁にランダムアクセスを必要とするアプリケーションや、メモリが制約された環境では最適な選択肢ではないかもしれません。 データの特定の要件や特性を慎重に考慮することで、手元のタスクに最も適したデータ構造を選択することができます。

Iron SoftwareのIronPDFライブラリは、開発者がPDFドキュメントを簡単に作成、操作できるようにし、最新のアプリケーションを開発するための高度なスキルを可能にします。

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