How to empty a C# list?

CsharpProgrammingServer Side Programming

To empty a C# list, use the Clear() method.

Firstly, set a list and add elements −

List<string> myList = new List<string>()
{
   "one",
   "two",
   "three",
   "four",
   "five",
   "six"
};

Now, let us empty the list −

myList.Clear();

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      List<string> myList = new List<string>() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "six"
      };
      foreach(string str in myList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Elements in the list = "+myList.Count);
      // this makes a list empty
      myList.Clear();
      Console.WriteLine("Elements in the list after using Clear() = "+myList.Count);
   }
}

Output

one
two
three
four
five
six
Elements in the list = 6
Elements in the list after using Clear() = 0
raja
Published on 31-Aug-2018 09:12:09
Advertisements