📜  C#|从StringDictionary中删除所有条目

📅  最后修改于: 2021-05-30 01:36:13             🧑  作者: Mango

StringDictionary.Clear方法用于从StringDictionary中删除所有条目。

句法:

public virtual void Clear ();

异常:如果StringDictionary为只读,则此方法将提供NotSupportedException。

例子:

// C# code to remove all entries
// from the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        myDict.Add("E", "Elephant");
        myDict.Add("F", "Fish");
  
        // Displaying the keys and values in StringDictionary
        Console.WriteLine("The number of key/value pairs are : " + myDict.Count);
  
        foreach(DictionaryEntry dic in myDict)
        {
            Console.WriteLine(dic.Key + " " + dic.Value);
        }
  
        // Removing all entries from the StringDictionary
        myDict.Clear();
  
        // Displaying the keys and values in StringDictionary
        Console.WriteLine("The number of key/value pairs are : " + myDict.Count);
  
        foreach(DictionaryEntry dic in myDict)
        {
            Console.WriteLine(dic.Key + " " + dic.Value);
        }
    }
}
输出:
The number of key/value pairs are : 6
b Banana
c Cat
a Apple
f Fish
d Dog
e Elephant
The number of key/value pairs are : 0

注意:此方法是O(n)运算,其中n是Count。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringdictionary.clear?view=netframework-4.7.2