Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Removing all nodes from LinkedList in C#
The LinkedList<T> class in C# provides the Clear() method to remove all nodes from a LinkedList efficiently. This method removes all elements and sets the Count property to zero.
Syntax
Following is the syntax for the Clear() method −
public void Clear()
Parameters
The Clear() method does not take any parameters.
Return Value
The Clear() method does not return any value. It modifies the LinkedList by removing all nodes.
Using Clear() with Integer LinkedList
The following example demonstrates how to remove all nodes from a LinkedList containing integers −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
int[] num = {10, 20, 30, 40, 50};
LinkedList<int> list = new LinkedList<int>(num);
Console.WriteLine("LinkedList nodes...");
foreach (var n in list) {
Console.WriteLine(n);
}
Console.WriteLine("Count before Clear: " + list.Count);
list.Clear();
Console.WriteLine("Count after Clear: " + list.Count);
Console.WriteLine("LinkedList is empty now!");
foreach (var n in list) {
Console.WriteLine(n);
}
}
}
The output of the above code is −
LinkedList nodes... 10 20 30 40 50 Count before Clear: 5 Count after Clear: 0 LinkedList is empty now!
Using Clear() with String LinkedList
The following example shows how to clear a LinkedList containing string elements −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
LinkedList<string> list = new LinkedList<string>();
list.AddLast("A");
list.AddLast("B");
list.AddLast("C");
list.AddLast("D");
list.AddLast("E");
list.AddLast("F");
list.AddLast("G");
list.AddLast("H");
list.AddLast("I");
list.AddLast("J");
Console.WriteLine("Count of nodes = " + list.Count);
list.Clear();
Console.WriteLine("Count of nodes (updated) = " + list.Count);
}
}
The output of the above code is −
Count of nodes = 10 Count of nodes (updated) = 0
How It Works
When the Clear() method is called, it performs the following operations −
-
Removes all references between nodes in the LinkedList
-
Sets the
Countproperty to zero -
Enables garbage collection for all previously contained elements
-
Resets the LinkedList to an empty state
Conclusion
The Clear() method provides an efficient way to remove all nodes from a LinkedList in C#. After calling this method, the LinkedList becomes empty with a count of zero, and you can continue to add new elements as needed.
