C# Linked List (How It Works For Developers)
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:
- Data: Payload stored in the node. This can be of any data type depending on the implementation, such as integers, strings, objects, etc.
- 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
- Insertion: Adding a new node to the list at a specific position, such as the beginning, end, or middle.
- Deletion: Removing a specified object node from the list, and adjusting the pointers of neighboring nodes accordingly.
- Traversal: Iterating through the list to access or manipulate each node's data.
- 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
Code Explanation
- Create a new linked list of integers using
new LinkedList<int>()
. - Add specified value objects to the linked list.
- Traverse and print the elements of the linked list using a
foreach
loop. - Find/search for an element in the linked list.
- Insert an element at a specified node using the
Find
andAddAfter
methods. - Remove an existing node from the linked list using the
Remove
method.
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
- Add headers and footers to PDFs.
- Merge, split, add, copy, and delete PDF pages.
- Set passwords, permissions, and digital signatures.
- 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.
Provide a project name and location.
Select the required .NET version.
Install IronPDF from the Visual Studio Package manager like the one below.
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<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>";
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<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>";
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<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>"
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
Code Explanation
- First, we start by creating the content for the PDF, using a content string object. The content is generated as an HTML string.
- Create a new linked list of strings with
new LinkedList<string>()
. - Add elements to the linked list and also append information to the PDF content string.
- Print the elements of the linked list and append to the PDF content.
- Insert an element at a specific position using the
AddAfter
method; update content and print the resulting list. - Remove an element from the linked list using the
Remove
method, update content, and print the resulting list. - Finally, save the generated HTML content string to a PDF document using
ChromePdfRenderer
,RenderHtmlAsPdf
, andSaveAs
methods.
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.
Frequently Asked Questions
What is a linked list in C#?
A linked list in C# is a linear data structure composed of nodes, with each node containing data and a reference to the next node. This structure, unlike arrays, allows for dynamic memory allocation, enabling elements to be stored in non-contiguous memory locations.
How can I convert HTML to PDF in C#?
You can use IronPDF's RenderHtmlAsPdf
method to convert HTML strings into PDFs. It also allows you to convert HTML files into PDFs using RenderHtmlFileAsPdf
.
What are the types of linked lists in C#?
In C#, the main types of linked lists are singly linked lists, doubly linked lists, and circular linked lists. Singly linked lists have nodes with a single reference to the next node, doubly linked lists have references to both the next and previous nodes, and circular linked lists have the last node pointing back to the first node.
What basic operations can be performed on linked lists?
Linked lists support operations such as insertion (adding a new node), deletion (removing an existing node), traversal (iterating through the list), and searching (finding a node based on its data).
How do you implement a linked list in C#?
A linked list can be implemented in C# using the LinkedList
class from the System.Collections.Generic
namespace, which provides methods for adding, removing, and manipulating the nodes in the list.
What features does a PDF generation library provide?
A PDF generation library like IronPDF offers HTML to PDF conversion, text extraction, document merging and splitting, and setting document permissions, all within various .NET environments.
How can linked lists be used with PDF generation?
Linked lists can dynamically store and organize content, which can then be iterated over and converted into a PDF document using a library like IronPDF, facilitating content manipulation and output.
What are the advantages of using linked lists in software development?
Linked lists offer efficient insertions and deletions, dynamic resizing, and are beneficial for implementing dynamic data structures like stacks and queues. They are especially useful when frequent modifications are needed, though they lack random access capabilities.
What is the difference between singly and doubly linked lists?
The primary difference is that singly linked lists have nodes with a single reference to the next node, allowing one-way traversal, whereas doubly linked lists have nodes with references to both the next and previous nodes, allowing bidirectional traversal.
How can I generate a PDF from linked list data in C#?
You can iterate through the linked list to collect data and then use IronPDF's API to render this data into a PDF document. This involves leveraging methods like HtmlToPdf
to convert structured content into a professional PDF format.