C# LinkedList<T> class implements the linked list data structure. This class enables efficient insertion and deletion of elements. Duplicate elements are permitted within this data structure. The LinkedList<T> class is located within the System.Collections.Generic namespace.
It enables us to insert and delete elements at either the beginning or end of the index.
C# LinkedList__PRESERVE_6__ example
Let's examine a sample of a general LinkedList<T> class that stores items through AddLast and AddFirst functions and traverses elements using a for-each loop.
using System;
using System.Collections.Generic;
public class LinkedListExample
{
public static void Main(string[] args)
{
// Create a list of strings
var names = new LinkedList<string>();
names.AddLast("Sonoo Jaiswal");
names.AddLast("Ankit");
names.AddLast("Peter");
names.AddLast("Irfan");
names.AddFirst("John");//added to first index
// Iterate list element using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
John
Sonoo Jaiswal
Ankit
Peter
Irfan
Note: Unlike List, you cannot create LinkedList using Collection initializer.
C# LinkedList__PRESERVE_8__ example 2
Let's explore another instance of a general LinkedList<T> structure that stores values both preceding and following a designated node. The retrieval of this particular node is achieved by invoking the Find function.
using System;
using System.Collections.Generic;
public class LinkedListExample
{
public static void Main(string[] args)
{
// Create a list of strings
var names = new LinkedList<string>();
names.AddLast("Sonoo");
names.AddLast("Ankit");
names.AddLast("Peter");
names.AddLast("Irfan");
//insert new element before "Peter"
LinkedListNode<String> node=names.Find("Peter");
names.AddBefore(node, "John");
names.AddAfter(node, "Lucy");
// Iterate list element using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
Output:
Sonoo
Ankit
John
Peter
Lucy
Irfan
As demonstrated in the preceding result, the names "John" and "Lucy" are inserted both preceding and following the name "Peter".