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

C#에서 두 StringDictionary 개체가 같은지 확인하는 방법

C#에서 두 StringDictionary 개체가 서로 같은지 확인하려면 Equals() 메서드를 사용할 수 있습니다. 다만 주의할 점이 있습니다. StringDictionary 클래스는 Equals()를 재정의하지 않기 때문에, 내용이 아니라 참조(reference)를 기준으로 비교된다는 점입니다. 아래 예제를 통해 실제 동작 방식을 자세히 살펴보겠습니다.

예제 1: Equals() 메서드로 동일성 확인하기

using System;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringDictionary strDict1 = new StringDictionary();
        strDict1.Add("A", "John");
        strDict1.Add("B", "Andy");
        strDict1.Add("C", "Tim");
        strDict1.Add("D", "Ryan");
        strDict1.Add("E", "Kevin");
        strDict1.Add("F", "Katie");
        strDict1.Add("G", "Brad");

        StringDictionary strDict2 = new StringDictionary();
        strDict2.Add("A", "John");
        strDict2.Add("B", "Andy");
        strDict2.Add("C", "Tim");
        strDict2.Add("D", "Ryan");
        strDict2.Add("E", "Kevin");
        strDict2.Add("F", "Katie");
        strDict2.Add("G", "Brad");

        StringDictionary strDict3 = new StringDictionary();
        strDict3 = strDict2;

        Console.WriteLine("Dictionary2는 Dictionary3와 같은가? = " + strDict2.Equals(strDict3));
        Console.WriteLine("Dictionary1은 Dictionary3와 같은가? = " + strDict1.Equals(strDict3));
    }
}

출력 결과

Dictionary2는 Dictionary3와 같은가? = True
Dictionary1은 Dictionary3와 같은가? = False

위 결과에서 주목해야 할 부분이 있습니다. strDict1strDict2는 완전히 동일한 키-값 쌍을 담고 있음에도 불구하고, Equals()False를 반환했습니다. 그 이유는 다음과 같습니다.

  • strDict3 = strDict2; 코드로 인해 두 변수는 같은 개체를 참조하므로 True가 반환됩니다.
  • strDict1은 내용은 같지만 별도로 생성된 개체이므로 참조가 다르고, 따라서 False가 반환됩니다.

즉, StringDictionaryEquals()는 값이 아닌 참조 동일성을 비교한다는 점을 반드시 기억해야 합니다.

예제 2: 요소를 출력하면서 두 사전 비교하기

이번에는 각 StringDictionary에 담긴 요소를 화면에 출력한 뒤, 두 개체를 비교해 보겠습니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringDictionary strDict1 = new StringDictionary();
        strDict1.Add("A", "John");
        strDict1.Add("B", "Andy");
        strDict1.Add("C", "Tim");
        strDict1.Add("D", "Ryan");
        strDict1.Add("E", "Kevin");
        strDict1.Add("F", "Katie");
        strDict1.Add("G", "Brad");

        Console.WriteLine("StringDictionary1 요소...");
        foreach(DictionaryEntry d in strDict1) {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        StringDictionary strDict2 = new StringDictionary();
        strDict2.Add("A", "John");
        strDict2.Add("B", "Andy");
        strDict2.Add("C", "Tim");
        strDict2.Add("D", "Ryan");
        strDict2.Add("E", "Kevin");
        strDict2.Add("F", "Katie");
        strDict2.Add("G", "Brad");

        Console.WriteLine("\nStringDictionary2 요소...");
        foreach(DictionaryEntry d in strDict2) {
            Console.WriteLine(d.Key + " " + d.Value);
        }

        Console.WriteLine("\nDictionary2는 Dictionary1과 같은가? = " + strDict2.Equals(strDict1));
    }
}

출력 결과

StringDictionary1 요소...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

StringDictionary2 요소...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Dictionary2는 Dictionary1과 같은가? = False

출력 결과에서 또 하나 흥미로운 점을 발견할 수 있습니다. 코드에서는 키를 대문자("A", "B")로 추가했지만, 실제 출력에는 소문자(a, b)로 표시됩니다. 이는 StringDictionary키를 소문자로 변환하여 저장하고, 대소문자를 구분하지 않기 때문입니다.

내용 기반으로 비교하려면?

참조가 아닌 실제 내용을 기준으로 두 StringDictionary를 비교하고 싶다면, 직접 비교 로직을 작성해야 합니다. 다음과 같은 확장 메서드를 활용할 수 있습니다.

public static bool AreEqual(StringDictionary d1, StringDictionary d2) {
    if (d1.Count != d2.Count) return false;

    foreach (string key in d1.Keys) {
        if (!d2.ContainsKey(key) || d1[key] != d2[key]) {
            return false;
        }
    }
    return true;
}

이 방식은 먼저 두 사전의 요소 개수(Count)를 비교한 뒤, 모든 키와 해당 값을 하나씩 대조하여 완전히 일치하는지 검사합니다.

핵심 정리

  • StringDictionary.Equals()참조 동일성을 비교하며, 내용이 같아도 개체가 다르면 False를 반환합니다.
  • 동일한 개체를 가리키는 경우에만 True가 반환됩니다.
  • StringDictionary는 키를 소문자로 변환하여 저장하므로 대소문자를 구분하지 않습니다.
  • 내용 기반 비교가 필요하다면 Count와 키-값 순회를 이용한 사용자 정의 비교 메서드를 구현해야 합니다.