Visual C#을 사용하여 HashTable 컬렉션 작업

이 문서에서는 Visual C#에서 컬렉션을 사용하는 HashTable 방법을 소개합니다.

원래 제품 버전: Visual C#
원래 KB 번호: 309357

요약

해시를 사용하면 데이터를 검색하는 데 비용이 많이 드는 데이터 검색이 필요하지 않으므로 해시를 사용하여 데이터를 효율적으로 검색할 수 있습니다. 해시는 키 자체의 값을 사용하여 데이터를 찾습니다.

기본 클래스 라이브러리는 고유한 해시 테이블을 코딩할 필요가 없도록 네임스페이스에 정의된 System.Collections 클래스를 제공합니다HashTable.

샘플을 빌드하는 단계

HashTable 컬렉션은 (Key, Value) 쌍을 저장하고 을 Key 사용하여 해시하고 스토리지 위치를 가져옵니다. 는 Key 변경할 수 없으며 에 HashTable중복 항목이 있을 수 없습니다. 이 샘플에서는 간단한 Person 클래스의 여러 인스턴스를 사용하여 에 HashTable저장합니다. 성은 로 Key사용됩니다.

  1. Microsoft Visual Studio를 열고 Visual C#에서 Windows Forms 애플리케이션 프로젝트를 만듭니다. 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;
        }
    }
    

    클래스에는 PersonLastName 매개 변수를 FirstName 사용하고 이러한 매개 변수를 지역 변수에 할당하는 하나의 생성자가 있습니다. 함수는 ToString 클래스에서 를 재정 ToStringObject 하여 함께 반환 Fname 하고 Lname 연결합니다.

  4. 양식 수준 Hashtable 개체를 만들고 형식 Person의 변수 3개를 선언합니다. 다음 코드를 Form1 클래스에 추가합니다.

    <?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. 다음 단계에서는 개체의 메서드를 Add 사용하여 블록의 Hashtable 에 세 개의 Person 개체를 Hashtabletry-catch 추가합니다. 블록은 try-catch 예외를 catch하고 중복 키가 있는 경우 메시지를 표시합니다.

    1. Form1에 단추 컨트롤을 놓고 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. Button 컨트롤을 Form1에 추가하고 Name 속성을 항목 가져오기로 변경합니다.

    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 사용하여 컬렉션에서 HashTable 단일 항목을 제거합니다.

    1. Button 컨트롤을 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. Button 컨트롤을 Form1에 추가하고 Text 속성을 Clear로 변경 합니다.

    2. 단추를 두 번 클릭하고 이벤트에 다음 코드를 붙여넣습니다 Button5_Click .

      MyTable.Clear();
      MessageBox.Show("HashTable is now empty");
      
  10. 애플리케이션을 빌드하고 실행하려면 다음 단계를 수행합니다.

    1. 항목 추가를 선택합니다. 컬렉션에 세 Person 개의 개체가 HashTable 추가됩니다.
    2. 항목 가져오기를 선택합니다. 인덱서는 컬렉션의 항목을 HashTable 가져옵니다. 새로 추가된 세 개의 항목이 표시됩니다.
    3. 항목 제거를 선택합니다. 키 위치의 Burris 항목이 삭제됩니다.
    4. 열거를 선택합니다. IDictionaryEnumerator 컬렉션의 항목을 HashTable 열거하고 의 속성은 KeysHashTable 키 컬렉션을 반환합니다.
    5. 지우기 를 선택합니다. 모든 항목은 컬렉션에서 HashTable 지워집니다.

참고

예제 회사, 조직, 제품, 도메인 이름, 전자 메일 주소, 로고, 사람, 장소 및 여기에 표시된 이벤트는 가상입니다. 실제 회사, organization, 제품, 도메인 이름, 이메일 주소, 로고, 사람, 장소 또는 이벤트와의 연관은 의도되거나 유추되어서는 안 됩니다.