📅  最后修改于: 2023-12-03 14:39:42.478000             🧑  作者: Mango
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#.
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.
// 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.
// 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.
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.