如何清空 C# 列表?


要清空 C# 列表,請使用 Clear() 方法。

首先,設定一個列表並新增元素 −

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

現在,讓我們清空列表 −

myList.Clear();

示例

 線上演示

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);
   }
}

輸出

one
two
three
four
five
six
Elements in the list = 6
Elements in the list after using Clear() = 0

更新於:2020 年 6 月 22 日

13K+ 瀏覽次數

啟動你的職業生涯

完成課程即可獲得證書

開始
廣告
© . All rights reserved.