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

C# Dictionary.Remove() 메서드 완벽 정리: 사전에서 키/값 쌍 제거하기

C#의 Dictionary.Remove() 메서드는 Dictionary<TKey, TValue> 컬렉션에서 지정한 키에 해당하는 키/값 쌍을 제거하는 데 사용됩니다.

구문

메서드 구문은 다음과 같습니다.

public bool Remove (TKey key);

여기서 매개변수 key는 사전에서 제거할 요소의 키입니다. 이 메서드는 지정한 키가 성공적으로 제거되면 true를 반환하고, 해당 키가 사전에 존재하지 않으면 false를 반환합니다. 참고로 키가 존재하지 않더라도 예외는 발생하지 않으므로 안전하게 호출할 수 있습니다.

예제 1

먼저 Dictionary.Remove() 메서드의 기본적인 사용 예제를 살펴보겠습니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("Removing some keys...");
      dict.Remove("Four");
      dict.Remove("Five");
      Console.WriteLine("Count of elements (updated) = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.Write("\nAll the keys..\n");
      Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
   }
}

실행 결과

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

Count of elements = 5
Removing some keys...
Count of elements (updated) = 3
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
All the keys..
Key = One
Key = Two
Key = Three

실행 결과를 보면 "Four"와 "Five" 키가 Remove() 메서드 호출 후 사전에서 제거되어 요소 개수가 5개에서 3개로 줄어든 것을 확인할 수 있습니다.

예제 2

이번에는 Remove() 메서드 호출 전후로 Keys 컬렉션의 변화를 비교하는 또 다른 예제를 살펴보겠습니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.Write("\nAll the keys..\n");
      Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
      Console.WriteLine("Removing some keys...");
      dict.Remove("Four");
      dict.Remove("Five");
      Console.WriteLine("Count of elements (updated) = "+dict.Count);
      Console.Write("\nAll the keys..updated\n");
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
   }
}

실행 결과

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

Count of elements = 5
All the keys..
Key = One
Key = Two
Key = Three
Key = Four
Key = Five
Removing some keys...
Count of elements (updated) = 3
All the keys..updated
Key = One
Key = Two
Key = Three
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers

정리

Dictionary.Remove() 메서드는 키를 기준으로 사전에서 항목을 손쉽게 삭제할 수 있는 방법을 제공합니다. 제거할 키가 존재하지 않아도 예외가 발생하지 않으며, 반환되는 bool 값을 활용하면 제거 성공 여부를 프로그램 로직에 반영할 수도 있습니다.