Visual C# を使用して HashTable コレクションを操作する

この記事では、Visual C# でコレクションを使用する HashTable 方法について説明します。

元の製品バージョン: Visual C#
元の KB 番号: 309357

概要

ハッシュを使用すると、データを取得するためにコストのかかるデータ検索が不要になるため、ハッシュを使用してデータを効率的に取得できます。 ハッシュでは、キー自体の値を使用してデータを検索します。

基底クラス ライブラリには、独自の HashTable ハッシュ テーブルを System.Collections コーディングする必要がないように、名前空間で定義されているクラスが用意されています。

サンプルをビルドする手順

コレクションは HashTable (Key、) ペアを格納し、 ValueKey 使用して、ストレージの場所をハッシュして取得します。 Keyは不変であり、 に重複するエントリをHashTable含めることはできません。 このサンプルでは、 に格納する単純な Person クラスのいくつかのインスタンスを HashTable使用します。 姓は として使用されます Key

  1. Microsoft Visual Studio を開き、Visual C# でWindows フォーム アプリケーション プロジェクトを作成します。 Form1 は既定でプロジェクトに追加されます。

  2. ソリューション エクスプローラーでプロジェクト名を右クリックし、[追加] をポイントし、[クラス] を選択してクラス モジュールを追加します。 Class1 は既定でプロジェクトに追加されます。

  3. モジュール内の任意のコードを Class1 次のコードに置き換えます。

    public class Person
    {
        public string Fname, Lname;d
        public Person (string FirstName, string LastName)
        {
            Fname = FirstName;
            Lname = LastName;
        }
        public override string ToString ()
        {
            return Fname + " " + Lname;
        }
    }
    

    Personクラスには、 と LastName パラメーターをFirstName受け取り、これらのパラメーターをローカル変数に割り当てるコンストラクターが 1 つあります。 関数はToString、 クラスからObjectをオーバーライドしてを返Fnameし、LnameToString連結します。

  4. フォーム レベル Hashtable のオブジェクトを作成し、 型の 3 つの変数を宣言します PersonForm1 クラスに以下のコードを追加します。

    <?xm-deletion_mark author="v-bobbid" time="20080711T172143-0800"
    data="private Hashtable MyTable = new Hashtable();
    
    //For simplicity, create three Person objects to add to the HashTable collection.
    
    Person Person1,Person2,Person3; "?>
    <?xm-insertion_mark_start author="v-bobbid" time="20080711T172143-0800"?>
    System.Collections.Hashtable MyTable = new
    System.Collections.Hashtable();
    
    //For simplicity, create three Person objects to add to the HashTable collection.
    Person Person1,Person2,Person3;
    <?xm-insertion_mark_end?>
    
  5. 次の手順では、 オブジェクトの メソッドをAddHashtable使用して、 ブロック内の に 3 つのPersonオブジェクトをHashtabletry-catch追加します。 ブロックは try-catch 例外をキャッチし、重複するキーが存在する場合にメッセージを表示します。

    1. Form1 に Button コントロールを配置し、 Text プロパティを [項目の追加] に変更します。

    2. ボタンをダブルクリックして [コード] ウィンドウを開き、イベントに次のコードを Button1_Click 貼り付けます。

      Person1 = new Person("David", "Burris");
      Person2 = new Person("Johnny", "Carrol");
      Person3 = new Person("Ji", "Jihuang");
      
      //The Add method takes Key as the first parameter and Value as the second parameter.
      
      try
      {
          MyTable.Add(Person1.Lname, Person1);
          MyTable.Add(Person2.Lname, Person2);
          MyTable.Add(Person3.Lname, Person3);
      }
      catch (ArgumentException ae)
      {
          MessageBox.Show("Duplicate Key");
          MessageBox.Show(ae.Message);
      }
      
  6. オブジェクトは Hashtable インデクサーを提供します。 次の手順では、 を使用 Key してインデックスを作成し、ハッシュされた場所に格納されている値にアクセスします。

    1. ボタン コントロールを Form1 に追加し、[ 名前 ] プロパティを [アイテムの取得] に変更します。

    2. ボタンをダブルクリックし、イベントに次のコードを Button2_Click 貼り付けます。

      //Use the indexer of the Hashtable class to retrieve your objects. The indexer takes
      //Key as a parameter and accesses it with the Hashed location.
      try
      {
          MessageBox.Show(MyTable[Person1.Lname].ToString());
          MessageBox.Show(MyTable[Person2.Lname].ToString());
          MessageBox.Show(MyTable[Person3.Lname].ToString());
      }
      catch (NullReferenceException ex)
      {
          MessageBox.Show("Key not in Hashtable");
          MessageBox.Show(ex.Message);
      }
      
  7. 次の手順では、 メソッドを Remove 使用して、コレクションから 1 つの項目を HashTable 削除します。

    1. ボタン コントロールを Form1 に追加し、 Text プロパティを [アイテムの削除] に変更します。

    2. ボタンをダブルクリックし、イベントに次のコードを Button3_Click 貼り付けます。

      <?xm-deletion_mark author="v-bobbid" time="20080711T173011-0800" data="if (MyTable.Count == 0)
      {
          MessageBox.Show(&quot;There are no items in HashTable&quot;);
      }
      else
      {
          MessageBox.Show(&quot;The count before removing an Item is&quot; + &quot; &quot; + MyTable.Count);
          MessageBox.Show(&quot;Removing value stored at key value (Burris)&quot;);
          Remove the object that is stored at the Key value Person1.Lname.
          MyTable.Remove(Person1.Lname);
      }
      "?>
      <?xm-insertion_mark_start author="v-bobbid" time="20080711T173011-0800"?>if (MyTable.Count == 0)
      {
          MessageBox.Show("There are no items in HashTable");
      }
      else
      {
          MessageBox.Show("The count before removing an Item is" + " " + MyTable.Count);
          MessageBox.Show("Removing value stored at key value (Burris)");
          // Remove the object that is stored at the Key value Person1.Lname.
          MyTable.Remove(Person1.Lname);
      }
      <?xm-insertion_mark_end?>
      
  8. 次の手順では、コレクションに格納されている項目を HashTable 列挙します。

    1. Button コントロールを Form1 に追加し、 Text プロパティを [列挙] に変更します。

    2. ボタンをダブルクリックし、イベントに次のコードを Button4_Click 貼り付けます。

      <?xm-deletion_mark author="v-bobbid" time="20080711T174252-0800"
      data="IDictionaryEnumerator Enumerator;
      if (MyTable.Count == 0)
      MessageBox.Show(&quot;The hashtable is empty&quot;);
      else
      {
          MessageBox.Show(&quot;Enumerating through the Hashtable collection&quot;);
          Enumerator = MyTable.GetEnumerator();
      
          while (Enumerator.MoveNext())
          {
              MessageBox.Show(Enumerator.Value.ToString());
          }
      }
      
      ICollection MyKeys;
      
      if (MyTable.Count == 0)
       MessageBox.Show(&quot;The hashtable is empty&quot;);
      else
      {
          MessageBox.Show(&quot;Accessing keys property to return keys collection&quot;);
          MyKeys = MyTable.Keys;
      
          foreach (object Key in MyKeys)
          {
              MessageBox.Show(Key.ToString());
          }
      }
      "?>
      <?xm-insertion_mark_start author="v-bobbid" time="20080711T174252-0800"?>
      System.Collections.IDictionaryEnumerator Enumerator;
      
      if (MyTable.Count == 0)
          MessageBox.Show("The hashtable is empty");
      else
      {
          MessageBox.Show("Enumerating through the Hashtable collection");
          Enumerator = MyTable.GetEnumerator();
      
          while (Enumerator.MoveNext())
          {
              MessageBox.Show(Enumerator.Value.ToString());
          }
      }
      
      System.Collections.ICollection MyKeys;
      
      if (MyTable.Count == 0)
          MessageBox.Show("The hashtable is empty");
      else
      {
          MessageBox.Show("Accessing keys property to return keys collection");
          MyKeys = MyTable.Keys;
      
          foreach (object Key in MyKeys)
          {
              MessageBox.Show(Key.ToString());
          }
      }
      <?xm-insertion_mark_end?>
      

      このコードでは、型 IDictionaryEnumerator の変数を宣言し、コレクションの GetEnumerator メソッドを HashTable 呼び出します。 がEnumerator返されると、コードはコレクション内の項目を列挙し、 の HashTable メソッドをKeys使用してキーを列挙します。

  9. 次の手順では、 メソッドを Clear 使用して をクリアします HashTable

    1. ボタン コントロールを Form1 に追加し、 Text プロパティを Clear に変更します。

    2. ボタンをダブルクリックし、イベントに次のコードを Button5_Click 貼り付けます。

      MyTable.Clear();
      MessageBox.Show("HashTable is now empty");
      
  10. アプリケーションをビルドして実行するには、次の手順に従います。

    1. [ 項目の追加] を選択します。 コレクションに 3 つの Person オブジェクトが HashTable 追加されます。
    2. [ アイテムの取得] を選択します。 インデクサーはコレクション内の項目を HashTable 取得します。 新しく追加された 3 つの項目が表示されます。
    3. [ アイテムの削除] を選択します。 キーの場所にある Burris 項目が削除されます。
    4. [ 列挙] を選択します。 IDictionaryEnumerator はコレクション内の項目を HashTable 列挙し Keys 、 の プロパティは HashTable Keys Collection を返します。
    5. [ クリア] を選択します。 すべての項目がコレクションから HashTable クリアされます。

注:

企業、組織、製品、ドメイン名、電子メール アドレス、ロゴ、人、場所、およびここに示されているイベントの例は架空です。 実際の会社、organization、製品、ドメイン名、電子メール アドレス、ロゴ、人物、場所、またはイベントとの関連付けが意図されていないか、推論する必要はありません。