C# LinkedList<T> class uses the concept of linked list. It allows us to insert and delete elements fastly. It can have duplicate elements. It is found in System.Collections.Generic namespace.
It allows us to add and remove element at before or last index.
Let's see an example of generic LinkedList<T> class that stores elements using AddLast() and AddFirst() methods and iterates elements using 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(); 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); } } }
Let's see another example of generic LinkedList<T> class that stores elements before and after specific node. To get the specific node, we are calling Find() method.
using System; using System.Collections.Generic; public class LinkedListExample { public static void Main(string[] args) { // Create a list of strings var names = new LinkedList(); names.AddLast("Sonoo"); names.AddLast("Ankit"); names.AddLast("Peter"); names.AddLast("Irfan"); //insert new element before "Peter" LinkedListNode 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); } } }
As you can see in the above output "John" and "Lucy" are added before and after "Peter".