C#에서 StringCollection에 포함된 모든 문자열을 한 번에 제거하려면 Clear() 메서드를 사용하면 됩니다. 이 메서드는 컬렉션의 모든 요소를 삭제하며, 호출 후 Count 속성 값은 0이 됩니다.
아래 예제 코드를 통해 실제 동작 방식을 살펴보겠습니다.
예제 1
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("Array elements...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Does the specified string is in the StringCollection? = "+stringCol.Contains("800"));
Console.WriteLine("Total number of elements = "+stringCol.Count);
stringCol.Clear();
Console.WriteLine("\nWe have removed all the elements now..");
Console.WriteLine("Total number of elements now = "+stringCol.Count);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Array elements... 100 200 300 400 500 Does the specified string is in the StringCollection? = False Total number of elements = 5 We have removed all the elements now.. Total number of elements now = 0
코드 설명
먼저 문자열 배열을 생성한 뒤 AddRange() 메서드를 사용해 StringCollection에 요소들을 한꺼번에 추가합니다. Contains("800") 메서드는 지정된 문자열이 컬렉션에 존재하는지 확인하며, 해당 값이 없으므로 false를 반환합니다. 이후 Clear() 메서드를 호출하면 컬렉션의 모든 요소가 제거되고, Count 값이 5에서 0으로 변경되는 것을 확인할 수 있습니다.
예제 2
이번에는 알파벳 문자열을 담은 컬렉션으로 동일한 작업을 수행해 보겠습니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
Console.WriteLine("Array elements...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Count of elements = "+stringCol.Count);
stringCol.Clear();
Console.WriteLine("\nRemoved all the elements now...");
Console.WriteLine("Total number of elements now = "+stringCol.Count);
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Array elements... A B C D E F G H I J Count of elements = 10 Removed all the elements now... Total number of elements now = 0
정리
StringCollection의 Clear() 메서드는 별도의 매개변수 없이 호출만 하면 되며, 컬렉션에 저장된 모든 문자열을 즉시 제거합니다. 요소를 하나씩 삭제하는 Remove()나 RemoveAt()과 달리, 컬렉션 전체를 초기화해야 할 때 가장 간편하게 사용할 수 있는 방법입니다.