C#
 Computer >> コンピューター >  >> プログラミング >> C#

C#のDictionary.Remove()メソッドの使い方を徹底解説

C#のDictionary.Remove()メソッドは、Dictionary<TKey, TValue>から指定したキーに対応するキーと値のペアを削除するために使用されます。この記事では、Remove()メソッドの基本的な構文から、実際に動作するサンプルコードまでをわかりやすく解説します。

構文

Dictionary.Remove()メソッドの構文は以下のとおりです。

public bool Remove (TKey key);

引数 key には、削除したい要素のキーを指定します。戻り値は bool 型で、要素の削除に成功した場合は true、指定したキーがディクショナリ内に存在しなかった場合は false を返します。なお、存在しないキーを指定しても例外はスローされないため、安全に呼び出すことができます。

使用例1:キーを削除して要素数を確認する

まずは、基本的な使い方を見てみましょう。以下の例では、5つの要素を持つディクショナリから「Four」と「Five」の2つのキーを削除しています。

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("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.Write("\nAll the keys..\n");
      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

「Four」と「Five」のキーが削除され、要素数が5から3に減っていることが確認できます。

使用例2:削除前後でキーの一覧を比較する

次に、削除前と削除後でキーの一覧がどのように変化するかを確認する例を紹介します。

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("\nAll the keys..\n");
      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("\nAll the keys..updated\n");
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
      Console.WriteLine("\nKey/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

この例では、dict.Keysプロパティで取得したKeyCollectionがディクショナリ本体と連動しているため、要素を削除した後に再度キーの一覧を出力すると、削除済みのキーが反映された状態になっていることがわかります。

まとめ

Dictionary.Remove()メソッドを使えば、指定したキーの要素を簡単に削除できます。ポイントは以下のとおりです。

  • 引数には削除対象のキーを指定する
  • 戻り値はbool型で、削除成功時はtrue、キーが存在しない場合はfalse
  • 存在しないキーを指定しても例外は発生しない

要素の動的な追加・削除が必要な場面では、ぜひ活用してみてください。

  1. Pythonの辞書からキーを削除する方法を解説!del文・pop()・popitem()の使い分け

    はじめに Pythonの辞書(dict)は、キーと値のペアでデータを管理できる非常に便利なデータ構造です。プログラムの実行中に不要になった要素を削除したい場面は多くありますが、Pythonにはいくつかの削除方法が用意されています。 この記事では、代表的な削除方法であるdel文とpop()メソッドを中心に、それぞれの特徴や使い分けのポイントを実行例とともにわかりやすく解説します。 del文でキーを削除する Pythonのdelキーワードは、ほぼすべてのオブジェクトに対して使用できます。辞書から特定の要素を削除する場合は、delステートメントにキーを指定します。 >>> D1

  2. スケルトンキー(Skeleton Key)の削除方法|企業ネットワークを狙うトロイの木馬への対処法

    企業ネットワークには、強固なセキュリティ対策と予防策を今すぐ導入すべき時が来ています。なぜなら、現在企業ネットワークを標的とする既知のマルウェアが存在するからです。その名は「スケルトンキー(Skeleton Key)」です。スケルトンキーとは?スケルトンキーは、企業ネットワークに属するセキュリティ対策が不十分なWindowsコンピューターを攻撃する危険なトロイの木馬です。専門家によると、この感染は主にシングルファクター認証(SFA)を利用しているシステムを狙う傾向があります。SFAとは、ワンステップのログインで完結する認証方式のことです。この方式では、ユーザーはアカウントにログインする際、ユー