Saltar al pie de página
.NET AYUDA

C# Linked List (Cómo Funciona para Desarrolladores)

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.

Preguntas Frecuentes

¿Qué es una lista enlazada en C#?

Una lista enlazada en C# es una estructura de datos lineal compuesta por nodos, donde cada nodo contiene datos y una referencia al siguiente nodo. Esta estructura, a diferencia de los arreglos, permite la asignación dinámica de memoria, permitiendo que los elementos se almacenen en ubicaciones de memoria no contiguas.

¿Cómo puedo convertir HTML a PDF en C#?

Puede usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas HTML en PDFs. También le permite convertir archivos HTML en PDFs usando RenderHtmlFileAsPdf.

¿Cuáles son los tipos de listas enlazadas en C#?

En C#, los principales tipos de listas enlazadas son las listas enlazadas simples, las listas enlazadas dobles y las listas enlazadas circulares. Las listas enlazadas simples tienen nodos con una sola referencia al siguiente nodo, las listas enlazadas dobles tienen referencias tanto al siguiente como al nodo anterior, y las listas enlazadas circulares tienen el último nodo apuntando de vuelta al primer nodo.

¿Qué operaciones básicas se pueden realizar en las listas enlazadas?

Las listas enlazadas admiten operaciones tales como inserción (agregar un nodo nuevo), eliminación (eliminar un nodo existente), recorrido (iterar a través de la lista) y búsqueda (encontrar un nodo basado en sus datos).

¿Cómo se implementa una lista enlazada en C#?

Se puede implementar una lista enlazada en C# usando la clase LinkedList del espacio de nombres System.Collections.Generic, que proporciona métodos para agregar, eliminar y manipular los nodos de la lista.

¿Qué características proporciona una biblioteca de generación de PDFs?

Una biblioteca de generación de PDFs como IronPDF ofrece conversión de HTML a PDF, extracción de texto, fusión y división de documentos, y establecimiento de permisos de documentos, todo dentro de varios entornos .NET.

¿Cómo se pueden usar las listas enlazadas con la generación de PDFs?

Las listas enlazadas pueden almacenar y organizar contenido dinámicamente, que luego puede ser iterado y convertido en un documento PDF utilizando una biblioteca como IronPDF, facilitando la manipulación y salida de contenido.

¿Cuáles son las ventajas de usar listas enlazadas en el desarrollo de software?

Las listas enlazadas ofrecen inserciones y eliminaciones eficientes, redimensionamiento dinámico, y son beneficiosas para implementar estructuras de datos dinámicas como pilas y colas. Son especialmente útiles cuando se necesitan modificaciones frecuentes, aunque carecen de capacidades de acceso aleatorio.

¿Cuál es la diferencia entre listas enlazadas simples y dobles?

La principal diferencia es que las listas enlazadas simples tienen nodos con una sola referencia al siguiente nodo, permitiendo un recorrido unidireccional, mientras que las listas enlazadas dobles tienen nodos con referencias tanto al siguiente como al nodo anterior, permitiendo un recorrido bidireccional.

¿Cómo puedo generar un PDF a partir de datos de una lista enlazada en C#?

Puede iterar a través de la lista enlazada para recopilar datos y luego usar la API de IronPDF para renderizar estos datos en un documento PDF. Esto implica aprovechar métodos como HtmlToPdf para convertir contenido estructurado en un formato PDF profesional.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más