C# 中的 Dictionary.Remove() 方法

csharpserver side programmingprogramming更新于 2025/11/26 10:12:00

C# 中的 Dictionary.Remove() 属性用于从 Dictionary<TKey, TValue> 中删除具有指定键的值。

语法

以下是语法 −

public bool Remove (TKey key);

上面,键是要删除的键。

示例

现在让我们看一个实现 Dictionary.Remove() 属性的示例 −

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("Removing some keys...");
      dict.Remove("Four");
      dict.Remove("Five");
      Console.WriteLine("Count of elements (updated) = "+dict.Count);
      Console.WriteLine("
Key/value pairs...");       foreach(KeyValuePair<string, string> res in dict){          Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);       }       Console.Write("
All the keys..
");       Dictionary<string, string>.KeyCollection allKeys = dict.Keys;       foreach(string str in allKeys){          Console.WriteLine("Key = {0}", str);       }    } }

输出

这将产生以下输出 −

Count of elements = 5
Removing some keys...
Count of elements (updated) = 3
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
All the keys..
Key = One
Key = Two
Key = Three

示例

现在让我们看另一个实现 Dictionary.Remove() 方法的示例 −

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.Write("
All the keys..
");       Dictionary<string, string>.KeyCollection allKeys = dict.Keys;       foreach(string str in allKeys){          Console.WriteLine("Key = {0}", str);       }       Console.WriteLine("Removing some keys...");       dict.Remove("Four");       dict.Remove("Five");       Console.WriteLine("Count of elements (updated) = "+dict.Count);       Console.Write("
All the keys..updated
");       foreach(string str in allKeys){          Console.WriteLine("Key = {0}", str);       }       Console.WriteLine("
Key/value pairs...");       foreach(KeyValuePair<string, string> res in dict){          Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);       }    } }

输出

这将产生以下输出 −

Count of elements = 5
All the keys..
Key = One
Key = Two
Key = Three
Key = Four
Key = Five
Removing some keys...
Count of elements (updated) = 3
All the keys..updated
Key = One
Key = Two
Key = Three
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers

相关文章