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

C# 컬렉션(Collection)에서 특정 개체의 첫 번째 항목만 제거하는 방법

C# 컬렉션에서 첫 번째 일치 항목 제거하기

Collection<T>에서 특정 개체가 처음으로 나타나는 항목 하나만 제거하려면 Remove() 메서드를 사용합니다.

Remove() 메서드는 지정한 개체와 일치하는 요소를 앞쪽부터 검색하여 가장 먼저 발견된 항목 하나만 삭제합니다. 나머지 동일한 값의 요소들은 그대로 유지되며, 요소가 성공적으로 제거되면 Count 값이 1 감소합니다. 만약 해당 개체가 컬렉션에 존재하지 않으면 컬렉션은 아무런 변화 없이 그대로 유지됩니다.

예제 1: 중복된 이름 중 첫 번째 항목만 제거

아래 예제에서는 "Nathan"이라는 값이 세 번 추가된 컬렉션에서 Remove("Nathan")을 호출했을 때, 첫 번째 "Nathan"만 제거되고 나머지 두 개는 남아 있는 것을 확인할 수 있습니다.

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("Andy");
      col.Add("Kevin");
      col.Add("John");
      col.Add("Nathan");
      col.Add("Nathan");
      col.Add("Katie");
      col.Add("Barry");
      col.Add("Nathan");
      col.Add("Mark");
      Console.WriteLine("Count of elements = "+ col.Count);
      Console.WriteLine("Iterating through the collection...");
      var enumerator = col.GetEnumerator();
      while (enumerator.MoveNext()) {
         Console.WriteLine(enumerator.Current);
      }
      col.Remove("Nathan");
      Console.WriteLine("Count of elements (updated) = "+ col.Count);
      Console.WriteLine("Iterating through the collection... (updated)");
      enumerator = col.GetEnumerator();
      while (enumerator.MoveNext()) {
         Console.WriteLine(enumerator.Current);
      }
   }
}

실행 결과

Count of elements = 9
Iterating through the collection...
Andy
Kevin
John
Nathan
Nathan
Katie
Barry
Nathan
Mark
Count of elements (updated) = 8
Iterating through the collection... (updated)
Andy
Kevin
John
Nathan
Katie
Barry
Nathan
Mark

결과 분석

초기 요소 개수는 9개였지만, Remove("Nathan") 실행 후 8개로 줄었습니다. 출력 결과를 보면 네 번째 위치에 있던 첫 번째 "Nathan"만 사라지고, 뒤에 있던 두 개의 "Nathan"은 그대로 남아 있는 것을 알 수 있습니다.

예제 2: 문자열 값으로 첫 번째 항목 제거

이번에는 "Two"라는 값이 세 번 포함된 컬렉션에서 첫 번째 "Two"만 제거해 보겠습니다.

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main(){
      Collection<string> col = new Collection<string>();
      col.Add("One");
      col.Add("Two");
      col.Add("Two");
      col.Add("Four");
      col.Add("Five");
      col.Add("Two");
      col.Add("Six");
      col.Add("Seven");
      Console.WriteLine("Count of elements = "+ col.Count);
      Console.WriteLine("Iterating through the collection...");
      var enumerator = col.GetEnumerator();
      while (enumerator.MoveNext()) {
         Console.WriteLine(enumerator.Current);
      }
      col.Remove("Two");
      Console.WriteLine("Count of elements = "+ col.Count);
      Console.WriteLine("Iterating through the collection... (updated)");
      enumerator = col.GetEnumerator();
      while (enumerator.MoveNext()) {
         Console.WriteLine(enumerator.Current);
      }
   }
}

실행 결과

Count of elements = 8
Iterating through the collection...
One
Two
Two
Four
Five
Two
Six
Seven
Count of elements = 7
Iterating through the collection... (updated)
One
Two
Four
Five
Two
Six
Seven

결과 분석

요소 개수가 8개에서 7개로 1개 줄었으며, 두 번째 위치에 있던 첫 번째 "Two"만 제거되고 다섯 번째와 여섯 번째 위치의 "Two"는 그대로 유지되었습니다.

참고: 모든 일치 항목을 제거하려면?

Remove()는 항상 첫 번째 항목 하나만 제거합니다. 동일한 값을 가진 모든 요소를 제거하고 싶다면 while 루프와 함께 사용하면 됩니다.

while (col.Remove("Nathan")) { } // "Nathan"이 더 이상 없을 때까지 반복 제거

또는 List<T>를 사용하는 경우라면 RemoveAll(x => x == "Nathan")처럼 조건자(predicate)를 이용해 한 번에 모든 일치 항목을 삭제할 수도 있습니다.