Remove all List C#

C# Remove All Element from List

You can remove all elements from a C# List, no questions asked.

In this tutorial, we shall learn how to remove all elements from a list. In other words, we shall make the list empty.

To remove or delete all the elements of a C# List, use List.Clear[] function.

The definition of List.Clear[] function is given below.

void List.Clear[]

Let us go through some working example, to implement Clear[] function on a List.

Example 1 Clear C# List

In this example, we shall initialize a list and some elements to it. Then we shall call Clear[] function on the list and remove all the elements from the list.

To verify if the list is empty, we shall print out length of the list.

Program.cs

using System; using System.Collections.Generic; class Program { static void Main[string[] args] { //create list List nums = new List[]; //add elements to the list nums.Add[56]; nums.Add[82]; nums.Add[94]; //remove all elements of nums nums.Clear[]; Console.WriteLine["Number of elements in the list : "+nums.Count]; } }

Run the above C# program.

Number of elements in the list : 0

All the elements are gone and the number of elements in the list is now zero.

Conclusion

In this C# Tutorial, we learned how to delete all the elements of a list in one go and make the list empty.

Video liên quan

Chủ Đề