從 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 key-value pairs...");
      foreach(DictionaryEntry de in strDict1) {
         Console.WriteLine(de.Key + " " + de.Value);
      }
      strDict1.Remove("D");
         Console.WriteLine("
StringDictionary1 key-value pairs after removing a key...");       foreach(DictionaryEntry de in strDict1) {          Console.WriteLine(de.Key + " " + de.Value);       }       StringDictionary strDict2 = new StringDictionary();       strDict2.Add("1", "A");       strDict2.Add("2", "B");       strDict2.Add("3", "C");       strDict2.Add("4", "D");       strDict2.Add("5", "E");       Console.WriteLine("
StringDictionary2 key-value pairs...");       IEnumerator demoEnum = strDict2.GetEnumerator();       DictionaryEntry d;       while (demoEnum.MoveNext()) {          d = (DictionaryEntry)demoEnum.Current;          Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);       }    } }

輸出

此程式碼將生成以下輸出:

StringDictionary1 key-value pairs...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

StringDictionary1 key-value pairs after removing a key...
a John
b Andy
c Tim
e Kevin
f Katie
g Brad

StringDictionary2 key-value pairs...
Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E

示例

讓我們看另一個示例:

 即時演示

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringDictionary strDict1 = new StringDictionary();
      strDict1.Add("A", "One");
      strDict1.Add("B", "Two");
      strDict1.Add("C", "Three");
      strDict1.Add("D", "Four");
      strDict1.Add("E", "Five");
      Console.WriteLine("StringDictionary1 key-value pairs...");
      foreach(DictionaryEntry de in strDict1) {
         Console.WriteLine(de.Key + " " + de.Value);
      }
      strDict1.Remove("B");
      strDict1.Remove("C");
      Console.WriteLine("
StringDictionary1 key-value pairs after removing a key...");       foreach(DictionaryEntry de in strDict1) {          Console.WriteLine(de.Key + " " + de.Value);       }    } }

輸出

此程式碼將生成以下輸出:

StringDictionary1 key-value pairs...
a One
b Two
c Three
d Four
e Five

StringDictionary1 key-value pairs after removing a key...
a One
d Four
e Five

更新日期:2019 年 12 月 5 日

70 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告