如何使用 C# 將詞典初始化為一個空詞典?


要將詞典初始化為一個空詞典,請使用 Clear() 方法。它將清除詞典並將其格式化為一個空詞典。

dict.Clear();

在此之後,使用 Dictionary 計數屬性來檢查列表是否為空 -

if (dict.Count == 0) {
   Console.WriteLine("Dictionary is empty!");
}

我們來看看完整的程式碼 -

示例

 現場演示

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

namespace Demo {
   public class Program {
      public static void Main(string[] args) {

         var dict = new Dictionary < string, string > ();
         dict.Clear();
         if (dict.Count == 0) {
            Console.WriteLine("Dictionary is empty!");
         }
      }
   }
}

輸出

Dictionary is empty!

更新於:2020 年 6 月 22 日

12K+ 檢視次數

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.