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

C# SortedList에서 모든 요소 제거하기 – Clear() 메서드 활용법

C# SortedList에서 모든 요소 한 번에 제거하기

C#의 SortedList에 저장된 모든 요소를 제거하려면 Clear() 메서드를 사용하면 됩니다. 이 메서드를 호출하면 SortedList에 포함된 모든 키-값 쌍이 삭제되고, Count 속성 값은 0으로 초기화됩니다.

다음 예제 코드를 통해 실제 동작 과정을 살펴보겠습니다.

예제 1: Clear() 메서드 기본 사용법

using System;
using System.Collections;
public class Demo {
    public static void Main(String[] args){
        SortedList sortedList = new SortedList();
        sortedList.Add("A", "1");
        sortedList.Add("B", "2");
        sortedList.Add("C", "3");
        sortedList.Add("D", "4");
        sortedList.Add("E", "5");
        sortedList.Add("F", "6");
        sortedList.Add("G", "7");
        sortedList.Add("H", "8");
        sortedList.Add("I", "9");
        sortedList.Add("J", "10");
        Console.WriteLine("SortedList elements...");
        foreach(DictionaryEntry d in sortedList){
            Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
        }
        Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
        sortedList.Clear();
        Console.WriteLine("Count of SortedList (updated) = "+sortedList.Count);
    }
}

출력 결과

SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs = 10
Count of SortedList (updated) = 0

실행 결과를 보면, Clear() 메서드를 호출하기 전에는 10개의 키-값 쌍이 저장되어 있었지만, 호출 직후 Count 값이 0으로 변경된 것을 확인할 수 있습니다. 즉, SortedList의 모든 요소가 한 번의 메서드 호출로 완전히 제거되었습니다.

예제 2: 요소 개수 확인 후 제거하기

이번에는 요소를 추가한 뒤 개수를 먼저 확인하고, Clear() 메서드로 전체를 제거한 후 다시 개수를 출력해 보겠습니다.

using System;
using System.Collections;
public class Demo {
    public static void Main(String[] args){
        SortedList sortedList = new SortedList();
        sortedList.Add("A", "1");
        sortedList.Add("B", "2");
        sortedList.Add("C", "3");
        Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
        Console.WriteLine("SortedList elements...");
        foreach(DictionaryEntry d in sortedList){
            Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
        }
        sortedList.Clear();
        Console.WriteLine("Count of SortedList key-value pairs (updated) = "+sortedList.Count);
    }
}

출력 결과

Count of SortedList key-value pairs = 3
SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Count of SortedList key-value pairs (updated) = 0

정리 및 참고 사항

SortedList의 모든 요소를 제거하는 가장 간단하고 확실한 방법은 Clear() 메서드를 호출하는 것입니다. 몇 가지 알아두면 좋은 특징은 다음과 같습니다.

- Clear() 메서드의 시간 복잡도는 O(n)입니다. 여기서 n은 SortedList에 포함된 요소의 개수입니다.
- 모든 요소를 제거한 후에도 SortedList의 용량(Capacity)은 그대로 유지됩니다.
- 용량까지 초기화하고 싶다면 Clear() 호출 후 TrimToSize() 메서드를 함께 사용하면 됩니다.

이처럼 Clear() 메서드 하나만으로 SortedList를 손쉽게 비울 수 있으므로, 컬렉션을 재사용하거나 초기화해야 하는 상황에서 매우 유용하게 활용할 수 있습니다.