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

C# SortedDictionary.Remove() 메서드 완벽 정리: 특정 키 요소 삭제하기

C#의 SortedDictionary.Remove() 메서드는 SortedDictionary<TKey, TValue> 컬렉션에서 지정한 키에 해당하는 요소를 삭제하는 데 사용됩니다. 이 메서드는 키가 성공적으로 제거되면 true를 반환하고, 해당 키가 컬렉션에 존재하지 않으면 false를 반환합니다.

문법(Syntax)

Remove() 메서드의 기본 문법은 다음과 같습니다.

public bool Remove (TKey key);

여기서 매개변수 key는 삭제하려는 요소의 키를 의미합니다.

주요 특징

  • 삭제할 키가 존재하면 요소를 제거하고 true를 반환합니다.
  • 삭제할 키가 존재하지 않아도 예외를 발생시키지 않고 false를 반환합니다.
  • 요소가 제거된 후에도 SortedDictionary는 자동으로 키 순서를 유지합니다.

예제 1

첫 번째 예제를 통해 Remove() 메서드의 사용법을 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("\nKey 400 removed from SortedDictionary? = "+sortedDict.Remove(400));
      Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      SortedDictionary<int, string>.KeyCollection keyColl = sortedDict.Keys;
      Console.WriteLine("\nKeys...list");
      foreach( int i in keyColl ){
         Console.WriteLine(i);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone
Key 400 removed from SortedDictionary? = True
SortedDictionary key-value pairs...UPDATED
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 500, Value = Headphone
Key = 600, Value = Earphone
Keys...list
100
200
300
500
600

출력 결과에서 확인할 수 있듯이, Remove(400) 호출 후 키 400에 해당하는 "Speakers" 항목이 사라졌으며, 메서드는 True를 반환했습니다. 또한 나머지 요소들은 여전히 키 기준 오름차순으로 정렬된 상태를 유지하고 있습니다.

예제 2

이번에는 다른 예제를 통해 Remove() 메서드를 더 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(1, "Ultrabook");
      sortedDict.Add(2, "Alienware");
      sortedDict.Add(3, "Notebook");
      sortedDict.Add(4, "Connector");
      sortedDict.Add(5, "Flash Drive");
      sortedDict.Add(6, "SSD");
      sortedDict.Add(7, "HDD");
      sortedDict.Add(8, "Earphone");
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      Console.WriteLine("\nKey 7 removed from SortedDictionary? = "+sortedDict.Remove(7));
      Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      SortedDictionary<int, string>.KeyCollection keyColl = sortedDict.Keys;
      Console.WriteLine("\nKeys...list");
      foreach( int i in keyColl ){
         Console.WriteLine(i);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

SortedDictionary key-value pairs...
Key = 1, Value = Ultrabook
Key = 2, Value = Alienware
Key = 3, Value = Notebook
Key = 4, Value = Connector
Key = 5, Value = Flash Drive
Key = 6, Value = SSD
Key = 7, Value = HDD
Key = 8, Value = Earphone
Key 7 removed from SortedDictionary? = True
SortedDictionary key-value pairs...UPDATED
Key = 1, Value = Ultrabook
Key = 2, Value = Alienware
Key = 3, Value = Notebook
Key = 4, Value = Connector
Key = 5, Value = Flash Drive
Key = 6, Value = SSD
Key = 8, Value = Earphone
Keys...list
1
2
3
4
5
6
8

정리

C#의 SortedDictionary.Remove() 메서드는 지정한 키의 요소를 안전하게 삭제할 수 있는 편리한 방법입니다. 존재하지 않는 키를 삭제하려 해도 예외가 발생하지 않으므로, 별도의 키 존재 여부 검사 없이 반환값(true/false)만으로 처리 결과를 확인할 수 있다는 점이 큰 장점입니다. 요소 삭제 후에도 컬렉션은 자동으로 정렬 상태를 유지하므로, 정렬된 키-값 데이터를 다루는 상황에서 유용하게 활용할 수 있습니다.