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

C#에서 두 SortedSet 객체가 동일한지 확인하는 방법

C#에서 두 SortedSet 객체 동일성 확인하기

C#에서 두 개의 SortedSet<T> 객체가 동일한지 확인하려면 Equals() 메서드를 사용할 수 있습니다. 다음 예제 코드를 통해 확인 방법을 살펴보겠습니다.

예제 1

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedSet<int> set1 = new SortedSet<int>();
      set1.Add(100);
      set1.Add(200);
      set1.Add(300);
      set1.Add(400);
      Console.WriteLine("Elements in SortedSet1...");
      foreach (int res in set1) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Does the SortedSet1 contains the element 400? = "+set1.Contains(400));

      SortedSet<int> set2 = new SortedSet<int>();
      set2.Add(100);
      set2.Add(200);
      set2.Add(300);
      set2.Add(400);
      Console.WriteLine("Elements in SortedSet2...");
      foreach (int res in set2){
         Console.WriteLine(res);
      }
      Console.WriteLine("Does the SortedSet2 contains the element 500? = "+set2.Contains(500));
      Console.WriteLine("Are both the sets equal? = "+set1.Equals(set2));
   }
}

출력 결과

Elements in SortedSet1...
100
200
300
400
Does the SortedSet1 contains the element 400? = True
Elements in SortedSet2...
100
200
300
400
Does the SortedSet2 contains the element 500? = False
Are both the sets equal? = False

결과 분석

위 예제에서 set1과 set2는 포함된 요소가 완전히 동일하지만(100, 200, 300, 400), 서로 다른 객체이기 때문에 Equals() 메서드는 False를 반환합니다. 참조 형식 객체에서 Equals()는 기본적으로 내용이 아닌 참조(메모리 주소)를 비교하기 때문입니다.

예제 2

이번에는 한 집합을 다른 변수에 할당한 후 동일성을 비교해 보겠습니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedSet<int> set1 = new SortedSet<int>();
      set1.Add(10);
      set1.Add(15);
      set1.Add(30);
      set1.Add(50);
      set1.Add(75);
      set1.Add(100);
      set1.Add(150);
      Console.WriteLine("Elements in SortedSet1...");
      foreach (int res in set1){
         Console.WriteLine(res);
      }
      Console.WriteLine("Does the SortedSet1 contains the element 400? = "+set1.Contains(400));

      SortedSet<int> set2 = new SortedSet<int>();
      set2.Add(25);
      set2.Add(50);
      set2.Add(100);
      set2.Add(200);
      set2.Add(400);
      set2.Add(500);
      Console.WriteLine("Elements in SortedSet2...");
      foreach (int res in set2){
         Console.WriteLine(res);
      }
      set2 = set1;
      Console.WriteLine("Are both the sets equal? = "+set1.Equals(set2));
   }
}

출력 결과

Elements in SortedSet1...
10
15
30
50
75
100
150
Does the SortedSet1 contains the element 400? = False
Elements in SortedSet2...
25
50
100
200
400
500
Are both the sets equal? = True

결과 분석

set2 = set1; 구문을 실행하면 set2는 set1과 같은 객체를 참조하게 됩니다. 즉, 두 변수가 동일한 인스턴스를 가리키므로 Equals() 메서드는 True를 반환합니다.

참고: 내용 기반 비교에는 SetEquals() 사용

두 집합의 요소 내용이 같은지 비교하고 싶다면 Equals() 대신 SetEquals() 메서드를 사용하는 것이 올바른 방법입니다. SetEquals()는 두 집합이 동일한 요소들을 포함하고 있는지 실제 내용을 기준으로 비교해 줍니다.

Console.WriteLine(set1.SetEquals(set2)); // 내용이 같으면 True 반환