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

C# SortedSet에서 요소 개수 구하기 - Count 속성 활용법

C#의 SortedSet<T> 클래스는 자동으로 정렬되는 고유한 요소들의 컬렉션을 제공합니다. 이 컬렉션에 저장된 요소의 개수를 확인하려면 Count 속성을 사용하면 됩니다. 이 속성은 집합에 현재 포함된 요소의 총 개수를 정수형(int)으로 반환합니다.

Count 속성의 기본 문법

int elementCount = sortedSet.Count;

예제 1: 문자열 SortedSet의 요소 수 확인

다음 예제에서는 두 개의 SortedSet을 생성하고, 각 집합의 요소를 출력한 후 Count 속성으로 요소 개수를 확인합니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedSet<string> set1 = new SortedSet<string>();
      set1.Add("AB");
      set1.Add("BC");
      set1.Add("CD");
      set1.Add("EF");

      Console.WriteLine("SortedSet1의 요소...");
      foreach (string res in set1) {
         Console.WriteLine(res);
      }

      Console.WriteLine("SortedSet1의 요소 개수 = " + set1.Count);

      SortedSet<string> set2 = new SortedSet<string>();
      set2.Add("BC");
      set2.Add("CD");
      set2.Add("DE");
      set2.Add("EF");
      set2.Add("AB");
      set2.Add("HI");
      set2.Add("JK");

      Console.WriteLine("SortedSet2의 요소 (열거자 사용)...");
      SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }

      Console.WriteLine("SortedSet2의 요소 개수 = " + set2.Count);
   }
}

출력 결과

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

SortedSet1의 요소...
AB
BC
CD
EF
SortedSet1의 요소 개수 = 4
SortedSet2의 요소 (열거자 사용)...
AB
BC
CD
DE
EF
HI
JK
SortedSet2의 요소 개수 = 7

예제 2: Clear 후 Count 값 변화 확인

Count 속성은 실시간으로 집합의 상태를 반영합니다. Clear() 메서드로 모든 요소를 제거하면 Count 값도 즉시 0으로 변경됩니다.

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("SortedSet의 요소...");
      foreach (int res in set1) {
         Console.WriteLine(res);
      }

      Console.WriteLine("SortedSet의 요소 개수 = " + set1.Count);

      // 모든 요소 제거
      set1.Clear();

      Console.WriteLine("SortedSet의 요소 개수 (업데이트 후) = " + set1.Count);
   }
}

출력 결과

SortedSet의 요소...
100
200
300
400
SortedSet의 요소 개수 = 4
SortedSet의 요소 개수 (업데이트 후) = 0

핵심 정리

  • Count 속성은 O(1) 시간 복잡도로 요소 개수를 반환하므로 성능 부담이 없습니다.
  • SortedSet은 중복 요소를 허용하지 않으므로, 이미 존재하는 값을 Add해도 Count가 늘어나지 않습니다.
  • Clear() 메서드 호출 후에는 Count가 항상 0을 반환합니다.
  • 집합이 비어 있는지 확인할 때는 Count == 0 대신 IsEmpty 관련 조건이나 Count 비교를 활용할 수 있습니다.