從 C# 中的 StringDictionary 中刪除所有條目


要從 StringDictionary 中刪除所有條目,程式碼如下 −

範例

 即時演練

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("A", "John");
      strDict1.Add("B", "Andy");
      strDict1.Add("C", "Tim");
      strDict1.Add("D", "Ryan");
      strDict1.Add("E", "Kevin");
      strDict1.Add("F", "Katie");
      strDict1.Add("G", "Brad");
      Console.WriteLine("StringDictionary1 elements...");
      foreach(DictionaryEntry d in strDict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Does StringDictionary1 has key G? "+strDict1.ContainsKey("G"));
      StringDictionary strDict2 = new StringDictionary();
      strDict2.Add("A", "John");
      strDict2.Add("B", "Andy");
      strDict2.Add("C", "Tim");
      strDict2.Add("D", "Ryan");
      strDict2.Add("E", "Kevin");
      strDict2.Add("F", "Katie");
      strDict2.Add("G", "Brad");
      Console.WriteLine("
StringDictionary2 elements...");       foreach(DictionaryEntry d in strDict2){          Console.WriteLine(d.Key + " " + d.Value);       }       Console.WriteLine("Count of key/value pairs in StringDictionary2 = " + strDict2.Count);       strDict2.Clear();       Console.WriteLine("Count of key/value pairs in StringDictionary2 (updated) = " + strDict2.Count);    } }

輸出

將產生以下輸出 −

StringDictionary1 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Does StringDictionary1 has key G? True
StringDictionary2 elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Count of key/value pairs in StringDictionary2 = 7
Count of key/value pairs in StringDictionary2 (updated) = 0

範例

讓我們看另一個示例 −

 即時演練

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict = new StringDictionary();
      strDict.Add("A", "John");
      strDict.Add("B", "Andy");
      strDict.Add("C", "Tim");
      strDict.Add("D", "Ryan");
      Console.WriteLine("StringDictionary elements...");
      foreach(DictionaryEntry d in strDict){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of key/value pairs in StringDictionary = " + strDict.Count);
      strDict.Clear();
      Console.WriteLine("Count of key/value pairs in StringDictionary (updated) = " + strDict.Count);
   }
}

輸出

將產生以下輸出 −

StringDictionary elements...
a John
b Andy
c Tim
d Ryan
Count of key/value pairs in StringDictionary = 4
Count of key/value pairs in StringDictionary (updated) = 0

更新於: 2019 年 12 月 4 日

63 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.