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

C# List에서 모든 요소 한 번에 제거하기 - Clear() 메서드 완벽 가이드

C#에서 List<T> 컬렉션의 모든 요소를 한 번에 제거하려면 Clear() 메서드를 사용하면 됩니다. 이 메서드는 리스트 내부의 모든 항목을 삭제하고 Count 속성을 0으로 만들어 줍니다.

Clear() 메서드란?

Clear()List<T> 클래스에서 제공하는 메서드로, 리스트에 저장된 모든 요소를 즉시 삭제합니다. 반환값은 없으며, 호출 후 리스트는 비어 있는 상태가 됩니다.

예제 1: 두 개의 리스트 비교 후 요소 제거하기

다음 예제에서는 두 개의 리스트를 생성한 뒤, Clear() 메서드를 호출하여 두 번째 리스트의 모든 요소를 제거하는 과정을 보여줍니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args) {
      List<String> list1 = new List<String>();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");
      list1.Add("Five");
      Console.WriteLine("List1의 요소...");
      foreach (string res in list1) {
         Console.WriteLine(res);
      }
      List<String> list2 = new List<String>();
      list2.Add("India");
      list2.Add("US");
      list2.Add("UK");
      list2.Add("Canada");
      list2.Add("Poland");
      list2.Add("Netherlands");
      Console.WriteLine("List2의 요소...");
      foreach (string res in list2) {
         Console.WriteLine(res);
      }
      Console.WriteLine("\nList2와 List1은 같은가? = " + list2.Equals(list1));
      Console.WriteLine("\nList2의 요소 개수 = " + list2.Count);
      list2.Clear();
      Console.WriteLine("\nList2의 요소 개수 (업데이트 후) = " + list2.Count);
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

List1의 요소...
One
Two
Three
Four
Five
List2의 요소...
India
US
UK
Canada
Poland
Netherlands
List2와 List1은 같은가? = False
List2의 요소 개수 = 6
List2의 요소 개수 (업데이트 후) = 0

출력 결과를 보면 Clear() 메서드 호출 전에는 요소 개수가 6이었지만, 호출 후에는 0으로 변경된 것을 확인할 수 있습니다.

예제 2: 단일 리스트의 요소 제거하기

이번에는 하나의 리스트만 사용하여 요소를 제거하는 더 간단한 예제를 살펴보겠습니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args) {
      List<String> list = new List<String>();
      list.Add("One");
      list.Add("Two");
      list.Add("Three");
      list.Add("Four");
      list.Add("Five");
      Console.WriteLine("리스트의 요소...");
      foreach (string res in list) {
         Console.WriteLine(res);
      }
      Console.WriteLine("\n리스트의 요소 개수 = " + list.Count);
      list.Clear();
      Console.WriteLine("\n리스트의 요소 개수 (업데이트 후) = " + list.Count);
   }
}

실행 결과

리스트의 요소...
One
Two
Three
Four
Five
리스트의 요소 개수 = 5
리스트의 요소 개수 (업데이트 후) = 0

정리

  • List.Clear() 메서드는 리스트의 모든 요소를 한 번에 제거합니다.
  • 요소 제거 후 Count 속성 값은 0이 됩니다.
  • 개별 요소를 제거하려면 Remove()RemoveAt() 메서드를 사용하고, 전체 삭제 시에는 Clear()가 가장 효율적입니다.