如何在 C# 中將列表初始化為一個空列表?


如需將列表初始化為 C# 中的空列表,請按以下語句進行設定,不含任何元素 −

List<string> list = new List<string>();

現在,使用 Any() 方法 檢查列表是否為空 −

bool chk = !list.Any();

讓我們看看完整程式碼 −

示例

 即時演示

using System;
using System.Collections.Generic;
using System.Linq;

public class Program {

   public static void Main() {
      // empty list
      List<string> list = new List<string>();

      // check for empty list
      bool chk = !list.Any();

      if(chk) {
         Console.WriteLine("List is Empty!");
      } else {
         Console.WriteLine("List isn't Empty!");
      }
   }
}

輸出

List is Empty!

更新於: 06-09-2023

45K+ 瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告