Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 Hashtable이 다른 Hashtable과 같은지 확인하는 방법

C#에서 하나의 Hashtable이 다른 Hashtable과 동일한지 확인하려면 Equals() 메서드를 사용하면 됩니다. 이 메서드는 두 Hashtable에 저장된 키(Key)와 값(Value) 쌍 전체를 비교하여, 모든 요소가 완전히 일치하면 true를 반환하고 하나라도 다르면 false를 반환합니다.

예제 1

다음 코드는 두 개의 Hashtable을 생성하고 Equals() 메서드로 서로 같은지 비교하는 과정을 보여줍니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Hashtable hash1 = new Hashtable();
      hash1.Add("1", "Kevin");
      hash1.Add("2", "Steve");
      hash1.Add("3", "Tim");
      hash1.Add("4", "Gary");
      hash1.Add("5", "Kevin");
      hash1.Add("6", "Steve");
      hash1.Add("7", "Tom");
      hash1.Add("8", "Stephen");
      Console.WriteLine("HashSet1...");
      ICollection key = hash1.Keys;
      foreach (string k in key) {
         Console.WriteLine(k + ": " + hash1[k]);
      }
      Hashtable hash2 = new Hashtable();
      hash2.Add("1", "Kevin");
      hash2.Add("2", "Steve");
      hash2.Add("3", "John");
      hash2.Add("4", "Tim");
      key = hash2.Keys;
      Console.WriteLine("\nHashSet2...");
      foreach (string k in key) {
         Console.WriteLine(k + ": " + hash2[k]);
      }
      Console.WriteLine("\nAre both the Hashtable equal? "+(hash1.Equals(hash2)));
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

HashSet1...
1: Kevin
2: Steve
3: Tim
4: Gary
5: Kevin
6: Steve
7: Tom
8: Stephen
HashSet2...
1: Kevin
2: Steve
3: John
4: Tim
Are both the Hashtable equal? False

첫 번째 Hashtable에는 8개의 항목이, 두 번째 Hashtable에는 4개의 항목이 들어 있으며, 값의 구성도 서로 다르기 때문에 비교 결과는 False가 됩니다.

예제 2

이번에는 항목 수가 비슷하지만 값이 일부만 겹치는 경우를 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      Hashtable hash1 = new Hashtable();
      hash1.Add("1", "Kevin");
      hash1.Add("2", "Steve");
      hash1.Add("3", "John");
      hash1.Add("4", "Tim");
      Console.WriteLine("HashSet1...");
      ICollection key = hash1.Keys;
      foreach (string k in key) {
         Console.WriteLine(k + ": " + hash1[k]);
      }
      Hashtable hash2 = new Hashtable();
      hash2.Add("1", "Nathan");
      hash2.Add("2", "Gary");
      hash2.Add("3", "John");
      hash2.Add("4", "Tim");
      hash2.Add("5", "Steve");
      ICollection key2 = hash2.Keys;
      Console.WriteLine("\nHashSet2...");
      foreach (string k in key2) {
         Console.WriteLine(k + ": " + hash2[k]);
      }
      Console.WriteLine("\nAre both the Hashtable equal? "+(hash1.Equals(hash2)));
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

HashSet1...
1: Kevin
2: Steve
3: John
4: Tim
HashSet2...
1: Nathan
2: Gary
3: John
4: Tim
5: Steve
Are both the Hashtable equal? False

정리

두 예제 모두에서 비교 결과가 false로 나온 이유는 Hashtable의 동등성 비교는 키와 값의 모든 쌍이 정확히 일치해야 하기 때문입니다. 일부 항목만 같거나 항목 수가 다르면 Equals() 메서드는 항상 false를 반환합니다. 따라서 두 Hashtable이 완전히 동일한 데이터를 담고 있는지 검증할 때는 Equals() 메서드가 가장 간단하고 확실한 방법입니다.