0
0
CsharpConceptBeginner · 3 min read

What is LinkedList in C#: Explanation and Example

LinkedList in C# is a collection that stores elements as nodes linked together in a sequence. Each node holds a value and references to the next and previous nodes, allowing efficient insertion and removal anywhere in the list.
⚙️

How It Works

A LinkedList in C# works like a chain of connected boxes, where each box (called a node) holds some data and links to the boxes before and after it. This means you can easily add or remove boxes anywhere in the chain without shifting all other boxes, unlike arrays.

Imagine a train where each carriage knows the one before and after it. If you want to add a new carriage, you just connect it to the right place without moving the whole train. This makes LinkedList great for situations where you often add or remove items in the middle.

💻

Example

This example shows how to create a LinkedList, add items, and print them in order.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        LinkedList<string> fruits = new LinkedList<string>();
        fruits.AddLast("Apple");
        fruits.AddLast("Banana");
        fruits.AddFirst("Cherry");

        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
Output
Cherry Apple Banana
🎯

When to Use

Use a LinkedList when you need to frequently add or remove items from the start, middle, or end of a list without the cost of shifting elements, which happens in arrays or lists. It is useful in scenarios like implementing undo/redo features, managing playlists, or any case where order matters and changes happen often.

However, if you mostly access items by index or rarely modify the list, a List<T> might be faster and simpler.

Key Points

  • LinkedList stores elements as nodes linked by references.
  • Each node knows its previous and next node, enabling easy insertion and removal.
  • Good for frequent insertions/removals anywhere in the list.
  • Not ideal for fast random access by index.

Key Takeaways

LinkedList stores elements as connected nodes with links to neighbors.
It allows fast insertion and removal anywhere without shifting elements.
Best used when list changes often in the middle or ends.
Not suitable for quick access by position; use List for that.