Delete all items from a List in C#
This post will discuss how to delete all items from a list in C#.
1. Using List<T>.Clear() Method
A simple and straightforward solution to remove all elements from a list is using the List<T>.Clear() method. The following example demonstrates usage of the Clear() method to remove all items from a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5}; nums.Clear(); Console.WriteLine(nums.Count); // 0 } } |
2. Using List<T>.Remove() Method
The List<T>.Remove(T) method is used to remove the first occurrence of a specified element from the List<T>. It can be used as follows to remove all items from a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5}; for (int i = nums.Count - 1; i >= 0; i--) { nums.Remove(nums[i]); } Console.WriteLine(nums.Count); // 0 } } |
Alternatively, we can use the List<T>.RemoveAt(Int32) method that takes the index of the List<T> and remove the element at that index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5}; for (int i = nums.Count - 1; i >= 0; i--) { nums.RemoveAt(i); } Console.WriteLine(nums.Count); // 0 } } |
3. Using List Constructor
Finally, we can simply assign the list to a new empty list instead of calling Clear() or remove individual items via looping and let the garbage collection kick in. Please note that any other references to the original list object will not be cleared.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5}; nums = new List<int>(); Console.WriteLine(nums.Count); // 0 } } |
That’s all about deleting all items from a list in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)