C#에서 두 개의 SortedList 객체가 동일한지 확인하려면 Equals() 메서드를 사용하면 됩니다. 이 메서드는 현재 객체와 비교 대상 객체가 같은 인스턴스를 참조하고 있는지 판단하여, 동일하면 true, 그렇지 않으면 false를 반환합니다.
예제 1 – 참조가 같은 경우
아래 예제에서는 두 개의 SortedList를 생성하고, 한 객체를 다른 변수에 할당한 뒤 Equals() 메서드로 동일성을 검사합니다 −
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two", 2);
list1.Add("Three", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven", 7);
list1.Add("Eight", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("SortedList1 요소...");
foreach(DictionaryEntry d in list1) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list2 = new SortedList();
list2.Add("A", "액세서리");
list2.Add("B", "도서");
list2.Add("C", "스마트 웨어러블 기기");
list2.Add("D", "가전제품");
Console.WriteLine("\nSortedList2 요소...");
foreach(DictionaryEntry d in list2) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list3 = new SortedList();
list3 = list2;
Console.WriteLine("\nSortedList2와 SortedList3은 동일한가요? = " + list3.Equals(list2));
}
}
출력
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
SortedList1 요소... Eight 8 Five 5 Four 4 Nine 9 One 1 Seven 7 Six 6 Ten 10 Three 3 Two 2 SortedList2 요소... A 액세서리 B 도서 C 스마트 웨어러블 기기 D 가전제품 SortedList2와 SortedList3은 동일한가요? = True
list3 = list2; 구문은 새로운 객체를 생성하는 것이 아니라 list2가 가리키는 동일한 객체를 list3가 함께 참조하도록 하는 대입문입니다. 따라서 두 변수는 같은 인스턴스를 공유하므로 Equals() 메서드의 결과는 True가 됩니다.
예제 2 – 별개의 인스턴스인 경우
이번에는 각각 독립적으로 생성된 두 개의 SortedList 객체를 비교해 보겠습니다 −
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two", 2);
list1.Add("Three", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven", 7);
list1.Add("Eight", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("SortedList1 요소(키-값 쌍)...");
foreach(DictionaryEntry d in list1) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list2 = new SortedList();
list2.Add("A", "액세서리");
list2.Add("B", "도서");
list2.Add("C", "스마트 웨어러블 기기");
list2.Add("D", "가전제품");
Console.WriteLine("\nSortedList2 요소(키-값 쌍)...");
foreach(DictionaryEntry d in list2) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nSortedList2와 SortedList1은 동일한가요? = " + list2.Equals(list1));
}
}
출력
실행 결과는 다음과 같습니다 −
SortedList1 요소(키-값 쌍)... Eight 8 Five 5 Four 4 Nine 9 One 1 Seven 7 Six 6 Ten 10 Three 3 Two 2 SortedList2 요소(키-값 쌍)... A 액세서리 B 도서 C 스마트 웨어러블 기기 D 가전제품 SortedList2와 SortedList1은 동일한가요? = False
list1과 list2는 각각 별도로 생성된 서로 다른 인스턴스이므로 Equals() 메서드는 False를 반환합니다.
핵심 정리
SortedList 클래스는 Object.Equals()를 재정의하지 않기 때문에, Equals() 메서드는 저장된 내용이 아닌 참조(객체 동일성)를 기준으로 비교합니다. 즉, 두 SortedList에 담긴 키-값 쌍이 완전히 같더라도 서로 다른 인스턴스라면 false가 반환됩니다. 따라서 내용 자체를 비교하려면 Count 속성으로 요소 개수를 먼저 확인한 뒤, 각 키와 값을 반복문으로 하나씩 대조하는 추가 로직을 직접 구현해야 합니다.