C# LinkedList<T>
To add and remove an element before or after the last index, the concept of a linked list is used in the C# LinkedList<T> class, thus facilitating a fast insertion and deletion of the elements. Found in the System.Collections.Generic namespace, the duplicate elements can also be stored in the C# LinkedList<T> class. Unlike List, the Collection initializer can not be used to create a LinkedList class.
Example:
using System; using System.Collections.Generic; public class Example { public static void Main(string[] args) { // Create a list of strings var countries = new LinkedList(); countries.AddLast("India"); countries.AddLast("Mexico"); countries.AddLast("Canada"); countries.AddLast("Australia"); countries.AddFirst("Japan");//added to the first index // Iterate list element using foreach loop foreach (var country in countries) { Console.WriteLine(country); } } } |
Output:
Explanation:
In the above example, we are using the generic LinkedList<T> class. We are using the AddLast() and AddFirst() methods to store the elements and the for-each loop is used to iterate the elements. Here, we are adding the element “Japan” at the first index.
Example:
using System; using System.Collections.Generic; public class Example { public static void Main(string[] args) { // Create a list of strings var countries = new LinkedList(); countries.AddLast("India"); countries.AddLast("Mexico"); countries.AddLast("Japan"); countries.AddLast("Nepal"); //insert new elements before and after "Nepal" LinkedListNode node= countries.Find("Nepal"); countries.AddBefore(node, "Australia"); countries.AddAfter(node, "Canada"); // Iterate list element using foreach loop foreach (var country in countries) { Console.WriteLine(country); } } } |
Output:
Explanation:
In the above example, we are using the generic LinkedList<T> class to store the elements before and after a specific node. Here, the Find() method is called to get the specific node. We are adding the elements “Australia” and “Canada” before and after “Nepal” element.