📜  c# clear linkList - C# (1)

📅  最后修改于: 2023-12-03 14:39:42.478000             🧑  作者: Mango

C# Clear LinkedList

Introduction

In C#, a LinkedList is a collection of nodes, where each node contains a value and a reference to the next node in the list. Sometimes it's necessary to clear the contents of a LinkedList, i.e., remove all the nodes from it. This topic explains how to clear a LinkedList in C#.

Clearing a LinkedList

To clear a LinkedList in C#, you can either iterate through the list and remove each node or simply create a new instance of the LinkedList. Let's explore both approaches.

Approach 1: Iterating and Removing Nodes
// Assuming you have a LinkedList<T> named "list"

// Create an instance of LinkedListNode<T> pointing to the first node
LinkedListNode<T> currentNode = list.First;

while (currentNode != null)
{
    // Get the next node before removing the current node
    LinkedListNode<T> nextNode = currentNode.Next;

    // Remove the current node from the list
    list.Remove(currentNode);

    // Move to the next node
    currentNode = nextNode;
}

By iterating through the list and removing each node, you clear the entire LinkedList.

Approach 2: Creating a New Instance of LinkedList
// Assuming you have a LinkedList<T> named "list"

// Create a new instance of LinkedList with the same type as the original list
LinkedList<T> clearedList = new LinkedList<T>();

// The original list is now clear and ready for garbage collection

By creating a new instance of the LinkedList, you essentially clear the contents of the original list. The original list becomes eligible for garbage collection as it no longer has any references.

Conclusion

Clearing a LinkedList in C# can be achieved by iteratively removing each node or by creating a new instance of LinkedList. Both approaches effectively remove all the nodes from the list. Choose the approach that best fits your specific use case.