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

C# List에서 특정 요소 제거하기 – Remove() 메서드 완벽 가이드

C#에서 List<T> 컬렉션에 저장된 특정 요소를 제거할 때는 Remove() 메서드를 사용합니다. 이 메서드는 지정한 값과 일치하는 첫 번째 항목을 리스트에서 삭제하며, 제거에 성공하면 true를, 해당 요소가 존재하지 않으면 false를 반환합니다.

예제 1: 문자열 리스트에서 요소 제거

다음은 두 개의 문자열 리스트를 만들고, Remove() 메서드로 특정 요소를 삭제한 후 그 결과를 확인하는 예제입니다.

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);

      // "US" 요소 제거
      list2.Remove("US");

      Console.WriteLine("\nlist2의 요소 개수 (업데이트 후) = " + list2.Count);
      Console.WriteLine("List2의 요소... 업데이트됨");
      foreach (string res in list2) {
         Console.WriteLine(res);
      }
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

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

예제 2: 정수 리스트에서 요소 제거

이번에는 문자열이 아닌 정수형 리스트에서 특정 숫자를 제거하는 예제를 살펴보겠습니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(5);
      list.Add(10);
      list.Add(20);
      list.Add(50);
      list.Add(75);
      list.Add(100);

      Console.WriteLine("리스트의 요소...");
      foreach (int res in list) {
         Console.WriteLine(res);
      }

      Console.WriteLine("\n리스트의 요소 개수 = " + list.Count);

      // 값 50 제거
      list.Remove(50);

      Console.WriteLine("\n리스트의 요소 개수 (업데이트 후) = " + list.Count);
      Console.WriteLine("리스트의 요소... 업데이트됨");
      foreach (int res in list) {
         Console.WriteLine(res);
      }
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

리스트의 요소...
5
10
20
50
75
100
리스트의 요소 개수 = 6
리스트의 요소 개수 (업데이트 후) = 5
리스트의 요소... 업데이트됨
5
10
20
75
100

핵심 정리

  • Remove(T item): 리스트에서 지정한 값과 일치하는 첫 번째 요소를 제거합니다.
  • 요소가 성공적으로 제거되면 true, 찾지 못하면 false를 반환합니다.
  • 요소가 제거되면 Count 속성 값도 자동으로 감소합니다.
  • 조건에 맞는 모든 요소를 한 번에 제거하려면 RemoveAll() 메서드를 사용할 수 있습니다.
  • 인덱스를 기준으로 제거하려면 RemoveAt(int index) 메서드를 활용하세요.