Zum Fußzeileninhalt springen
.NET HILFE

C# Linked List (Funktionsweise für Entwickler)

A linked list is a linear data structure composed of a series of nodes, which can also be called elements. Unlike arrays, where elements/nodes are stored in contiguous memory locations, linked lists utilize dynamic memory allocation, allowing elements/nodes to be scattered throughout memory.

In its simplest form, "linked lists" consist of nodes linked together linearly. Each node contains two main parts:

  1. Data: Payload stored in the node. This can be of any data type depending on the implementation, such as integers, strings, objects, etc.
  2. Next Pointer: A reference (or pointer) to the next node in the sequence. This pointer indicates the memory location of the following node points forward in the linked list.

The last node in a linked list typically points to a null reference, indicating the end of the list.

In this article, we will look in detail at the Linked list in C# and also explore the IronPDF library, a PDF generation tool from Iron Software.

Types of Linked Lists

1. Singly Linked List

A singly linked list has a node with only one reference, typically pointing to the next node in the sequence. Traversing the list is limited to moving in one direction, typically from the head (the initial node) to the tail (the final node).

2. Doubly Linked List

In a doubly linked list, each node contains two references: one pointing to the next node and another pointing to the previous node in the sequence. This bidirectional linkage enables traversal in both forward and backward directions.

3. Circular Linked List

In a circular linked list, the last node points back to the first node, forming a circular structure. This type of linked list can be implemented using either singly or doubly linked nodes.

Basic Operations on Linked Lists

  1. Insertion: Adding a new node to the list at a specific position, such as the beginning, end, or middle.
  2. Deletion: Removing a specified object node from the list, and adjusting the pointers of neighboring nodes accordingly.
  3. Traversal: Iterating through the list to access or manipulate each node's data.
  4. Search: Finding a specific node in the list based on its data-specified value.

Linked List in C#

In C#, you can implement a linked list using the LinkedList class from the System.Collections.Generic namespace. Here's an example of all the basic operations:

using System;
using System.Collections.Generic;

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
            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);
            }

            // Display number of linked list elements
            Console.WriteLine($"Number of Linked List elements: {linkedList.Count}");

            // Find/Search for an element in the linked list
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);

            if (foundNode != null)
            {
                Console.WriteLine(
                    $"Found Value: {foundNode.Value}, " +
                    $"Next Element: {(foundNode.Next != null ? foundNode.Next.Value.ToString() : "null")}, " +
                    $"Previous Element: {(foundNode.Previous != null ? foundNode.Previous.Value.ToString() : "null")}"
                );
            }

            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            if (current != null)
            {
                linkedList.AddAfter(current, 25);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
            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);

            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
        }
    }
}
using System;
using System.Collections.Generic;

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
            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);
            }

            // Display number of linked list elements
            Console.WriteLine($"Number of Linked List elements: {linkedList.Count}");

            // Find/Search for an element in the linked list
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);

            if (foundNode != null)
            {
                Console.WriteLine(
                    $"Found Value: {foundNode.Value}, " +
                    $"Next Element: {(foundNode.Next != null ? foundNode.Next.Value.ToString() : "null")}, " +
                    $"Previous Element: {(foundNode.Previous != null ? foundNode.Previous.Value.ToString() : "null")}"
                );
            }

            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            if (current != null)
            {
                linkedList.AddAfter(current, 25);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
            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);

            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic

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

			' Display number of linked list elements
			Console.WriteLine($"Number of Linked List elements: {linkedList.Count}")

			' Find/Search for an element in the linked list
			Console.WriteLine(vbLf & "Find/Search Element Linked List elements: 30")
			Dim foundNode = linkedList.Find(30)

			If foundNode IsNot Nothing Then
				Console.WriteLine($"Found Value: {foundNode.Value}, " & $"Next Element: {(If(foundNode.Next IsNot Nothing, foundNode.Next.Value.ToString(), "null"))}, " & $"Previous Element: {(If(foundNode.Previous IsNot Nothing, foundNode.Previous.Value.ToString(), "null"))}")
			End If

			' Insert an element at a specified node
			Dim current As LinkedListNode(Of Integer) = linkedList.Find(20)
			If current IsNot Nothing Then
				linkedList.AddAfter(current, 25)
			End If

			Console.WriteLine($vbLf & "Number of Linked List elements: {linkedList.Count}")
			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)

			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}")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

  1. Create a new linked list of integers using new LinkedList<int>().
  2. Add specified value objects to the linked list.
  3. Traverse and print the elements of the linked list using a foreach loop.
  4. Find/search for an element in the linked list.
  5. Insert an element at a specified node using the Find and AddAfter methods.
  6. Remove an existing node from the linked list using the Remove method.

Output

C# Linked List (How It Works For Developers): Figure 1 - Linked List Output

Introducing IronPDF

Discover more about IronPDF is a powerful C# PDF library developed and maintained by Iron Software. It provides a comprehensive set of features for creating, editing, and extracting content from PDF documents within .NET projects.

Key Points about IronPDF

HTML to PDF Conversion

IronPDF allows you to convert HTML content to PDF format. You can render HTML pages, URLs, and HTML strings into PDFs with ease.

Rich API

The library offers a user-friendly API that enables developers to generate professional-quality PDFs directly from HTML. Whether you need to create invoices, reports, or other documents, IronPDF simplifies the process.

Cross-Platform Support

IronPDF is compatible with various .NET environments, including .NET Core, .NET Standard, and .NET Framework. It runs on Windows, Linux, and macOS platforms.

Versatility

IronPDF supports different project types, such as web applications (Blazor and WebForms), desktop applications (WPF and MAUI), and console applications.

Content Sources

You can generate PDFs from various content sources, including HTML files, Razor views (Blazor Server), CSHTML (MVC and Razor), ASPX (WebForms), and XAML (MAUI).

Additional Features

  1. Add headers and footers to PDFs.
  2. Merge, split, add, copy, and delete PDF pages.
  3. Set passwords, permissions, and digital signatures.
  4. Optimize performance with multithreading and asynchronous support.

Compatibility

IronPDF adheres to PDF standards, including versions 1.2 to 1.7, PDF/UA, and PDF/A. It also supports UTF-8 character encoding, base URLs, and asset encoding.

Generate PDF Document Using LinkedList

Now let's create a PDF document using IronPDF and also demonstrate the usage of LinkedList strings.

To start with, open Visual Studio and create a console application by selecting from project templates as shown below.

C# Linked List (How It Works For Developers): Figure 2 - New Project

Provide a project name and location.

C# Linked List (How It Works For Developers): Figure 3 - Project Configuration

Select the required .NET version.

C# Linked List (How It Works For Developers): Figure 4 - Target Framework

Install IronPDF from the Visual Studio Package manager like the one below.

C# Linked List (How It Works For Developers): Figure 5 - Install IronPDF

Or it can be installed using the below command line.

dotnet add package IronPdf --version 2024.4.2

Add the below code.

using System;
using System.Collections.Generic;
using IronPdf;

namespace 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>Create a new linked list of strings with new LinkedList&lt;string&gt;()</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>";
            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>";
            LinkedListNode<string> node = linkedList.Find("Banana");
            if (node != null)
            {
                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>";
            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 a PDF renderer
            var renderer = new ChromePdfRenderer();

            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Save to a file
            pdf.SaveAs("AwesomeIronOutput.pdf");
        }
    }
}
using System;
using System.Collections.Generic;
using IronPdf;

namespace 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>Create a new linked list of strings with new LinkedList&lt;string&gt;()</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>";
            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>";
            LinkedListNode<string> node = linkedList.Find("Banana");
            if (node != null)
            {
                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>";
            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 a PDF renderer
            var renderer = new ChromePdfRenderer();

            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Save to a file
            pdf.SaveAs("AwesomeIronOutput.pdf");
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports IronPdf

Namespace 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>Create a new linked list of strings with new LinkedList&lt;string&gt;()</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>"
			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>"
			Dim node As LinkedListNode(Of String) = linkedList.Find("Banana")
			If node IsNot Nothing Then
				linkedList.AddAfter(node, "Mango")
				content &= "<p>Find Banana and insert Mango After</p>"
			End If

			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>"
			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 a PDF renderer
			Dim renderer = New ChromePdfRenderer()

			' Create a PDF from HTML string
			Dim pdf = renderer.RenderHtmlAsPdf(content)

			' Save to a file
			pdf.SaveAs("AwesomeIronOutput.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Code Explanation

  1. First, we start by creating the content for the PDF, using a content string object. The content is generated as an HTML string.
  2. Create a new linked list of strings with new LinkedList<string>().
  3. Add elements to the linked list and also append information to the PDF content string.
  4. Print the elements of the linked list and append to the PDF content.
  5. Insert an element at a specific position using the AddAfter method; update content and print the resulting list.
  6. Remove an element from the linked list using the Remove method, update content, and print the resulting list.
  7. Finally, save the generated HTML content string to a PDF document using ChromePdfRenderer, RenderHtmlAsPdf, and SaveAs methods.

Output

C# Linked List (How It Works For Developers): Figure 6 - IronPDF with `LinkedList` Output

The output has a watermark that can be removed using a valid license from the IronPDF licensing page.

IronPDF License

The IronPDF library requires a license to run, and it can be obtained from the product licensing page.

Paste the key in the appSettings.json file below.

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

Conclusion

C# LinkedList provides a versatile data structure for managing collections of elements, offering efficient insertions and deletions while accommodating dynamic resizing, similar to the default hash function. Linked lists are commonly used in various applications and algorithms, such as implementing stacks, queues, symbol tables, and memory management systems. Understanding the characteristics and operations of linked lists is essential for building efficient and scalable software solutions.

In summary, while linked lists excel in certain scenarios, such as dynamic data structures and frequent insertions/deletions, they may not be the best choice for applications requiring frequent random access or dealing with memory-constrained environments. Careful consideration of the specific requirements and characteristics of the data can guide the selection of the most appropriate data structure for the task at hand.

The IronPDF library from Iron Software allows developers to create and manipulate PDF documents effortlessly, enabling advanced skills to develop modern applications.

Häufig gestellte Fragen

Was ist eine verkettete Liste in C#?

Eine verkettete Liste in C# ist eine lineare Datenstruktur, die aus Knoten besteht, wobei jeder Knoten Daten und eine Referenz auf den nächsten Knoten enthält. Diese Struktur ermöglicht im Gegensatz zu Arrays eine dynamische Speicherzuweisung, wodurch Elemente in nicht zusammenhängenden Speicherorten gespeichert werden können.

Wie kann ich HTML in PDF in C# konvertieren?

Sie können die RenderHtmlAsPdf-Methode von IronPDF verwenden, um HTML-Strings in PDFs zu konvertieren. Es ermöglicht auch die Konvertierung von HTML-Dateien in PDFs mit RenderHtmlFileAsPdf.

Was sind die Typen von verketteten Listen in C#?

In C# sind die Haupttypen von verketteten Listen einfach verkettete Listen, doppelt verkettete Listen und zirkuläre verkettete Listen. Einfach verkettete Listen verfügen über Knoten mit einer einzigen Referenz auf den nächsten Knoten, doppelt verkettete Listen haben Referenzen sowohl auf den nächsten als auch auf den vorherigen Knoten, und zirkuläre verkettete Listen haben den letzten Knoten, der auf den ersten Knoten zeigt.

Welche grundlegenden Operationen gibt es für verkettete Listen?

Verkettete Listen unterstützen Operationen wie Einfügen (Hinzufügen eines neuen Knotens), Löschen (Entfernen eines vorhandenen Knotens), Durchlauf (Iterieren durch die Liste) und Suche (Finden eines Knotens basierend auf seinen Daten).

Wie implementiert man eine verkettete Liste in C#?

Eine verkettete Liste kann in C# mit der LinkedList-Klasse aus dem System.Collections.Generic-Namespace implementiert werden, die Methoden zum Hinzufügen, Entfernen und Manipulieren der Knoten in der Liste bereitstellt.

Welche Funktionen bietet eine PDF-Generierungsbibliothek?

Eine PDF-Generierungsbibliothek wie IronPDF bietet HTML-zu-PDF-Konvertierung, Textextraktion, Dokumentenzusammenführung und -trennung sowie das Setzen von Dokumentenberechtigungen, alles innerhalb verschiedener .NET-Umgebungen.

Wie können verkettete Listen mit der PDF-Generierung verwendet werden?

Verkettete Listen können dynamisch Inhalte speichern und organisieren, die dann iteriert und mithilfe einer Bibliothek wie IronPDF in ein PDF-Dokument umgewandelt werden können, was die Inhaltsmanipulation und -ausgabe erleichtert.

Welche Vorteile bieten verkettete Listen in der Softwareentwicklung?

Verkettete Listen bieten effiziente Einfügungen und Löschungen, dynamische Größeneinstellung und sind vorteilhaft für die Implementierung dynamischer Datenstrukturen wie Stacks und Warteschlangen. Sie sind besonders nützlich, wenn häufige Änderungen erforderlich sind, obwohl ihnen die Fähigkeit zum direkten Zugriff fehlt.

Was ist der Unterschied zwischen einfach und doppelt verketteten Listen?

Der Hauptunterschied besteht darin, dass einfach verkettete Listen Knoten mit einer einzigen Referenz auf den nächsten Knoten haben, was eine einseitige Durchlaufung ermöglicht, während doppelt verkettete Listen Knoten mit Referenzen sowohl auf den nächsten als auch auf den vorherigen Knoten haben, was eine bidirektionale Durchlaufung ermöglicht.

Wie kann ich ein PDF aus verketteten Listendaten in C# generieren?

Sie können durch die verkettete Liste iterieren, um Daten zu sammeln, und dann die API von IronPDF verwenden, um diese Daten in ein PDF-Dokument zu rendern. Dies beinhaltet die Nutzung von Methoden wie HtmlToPdf, um strukturierte Inhalte in ein professionelles PDF-Format umzuwandeln.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen