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

C# OrderedDictionary – 지정한 인덱스 위치에 키와 값으로 요소 삽입하기

C#의 OrderedDictionary 클래스는 키-값 쌍을 삽입한 순서 그대로 유지하는 컬렉션입니다. 이 컬렉션에는 Insert(int index, object key, object value) 메서드가 제공되며, 이를 사용하면 원하는 인덱스 위치에 새로운 키와 값을 삽입할 수 있습니다.

Insert() 메서드의 기본 개념

Insert 메서드는 세 가지 매개변수를 받습니다.

  • index : 요소가 삽입될 0부터 시작하는 위치
  • key : 삽입할 요소의 키
  • value : 삽입할 요소의 값

삽입이 완료되면 해당 위치 이후의 기존 요소들은 자동으로 한 칸씩 뒤로 밀려나며, 전체 요소 수도 하나 증가합니다.

예제 1 – 지정된 인덱스에 요소 삽입

다음 예제는 OrderedDictionary를 생성하고, 여기에 Insert 메서드를 사용해 특정 인덱스에 키와 값을 추가하는 방법을 보여줍니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "Books");
      dict.Add("B", "Electronics");
      dict.Add("C", "Smart Wearables");
      dict.Add("D", "Pet Supplies");
      Console.WriteLine("OrderedDictionary elements...");
      foreach(DictionaryEntry d in dict){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
      dict.Insert(4, "E", "Clothing");
      dict.Insert(5, "F", "Footwear");
      Console.WriteLine("OrderedDictionary elements...UPDATED");
      foreach(DictionaryEntry d in dict){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of elements in OrderedDictionary (UPDATED) = " + dict.Count);
      dict.Remove("E");
      Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 나타납니다.

OrderedDictionary elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
Count of elements in OrderedDictionary = 4
OrderedDictionary elements...UPDATED
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Count of elements in OrderedDictionary (UPDATED) = 6
Count of elements in OrderedDictionary (Updated)= 5

출력을 보면 인덱스 4와 5에 각각 "Clothing"과 "Footwear"가 순서대로 삽입되어 요소 수가 4개에서 6개로 늘어난 것을 확인할 수 있습니다. 이후 Remove() 메서드로 키 "E"를 제거하면 요소 수가 다시 5개로 줄어듭니다.

예제 2 – 두 컬렉션 비교 후 중간 위치에 삽입

이번 예제에서는 두 개의 OrderedDictionary를 만들어 서로 비교한 뒤, 중간 인덱스에 요소를 삽입하여 결과가 어떻게 달라지는지 살펴봅니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      OrderedDictionary dict1 = new OrderedDictionary();
      dict1.Add("A", "Books");
      dict1.Add("B", "Electronics");
      dict1.Add("C", "Smart Wearables");
      dict1.Add("D", "Pet Supplies");
      dict1.Add("E", "Clothing");
      dict1.Add("F", "Footwear");
      Console.WriteLine("OrderedDictionary1 elements...");
      foreach(DictionaryEntry d in dict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      OrderedDictionary dict2 = new OrderedDictionary();
      dict2.Add("1", "One");
      dict2.Add("2", "Two");
      dict2.Add("3", "Three");
      dict2.Add("4", "Four");
      dict2.Add("5", "Five");
      dict2.Add("6", "Six");
      Console.WriteLine("\nOrderedDictionary2 elements...");
      foreach(DictionaryEntry d in dict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("\nIs OrderedDictionary1 equal to OrderedDictionary2? = "+(dict1.Equals(dict2)));
      dict2.Insert(3, "10", "Ten");
      Console.WriteLine("\nOrderedDictionary2 elements...UPDATED");
      foreach(DictionaryEntry d in dict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("\nIs OrderedDictionary1 equal to OrderedDictionary2? = "+(dict1.Equals(dict2)));
   }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 나타납니다.

OrderedDictionary1 elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
OrderedDictionary2 elements...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Is OrderedDictionary1 equal to OrderedDictionary2? = False
OrderedDictionary2 elements...UPDATED
1 One
2 Two
3 Three
10 Ten
4 Four
5 Five
6 Six
Is OrderedDictionary1 equal to OrderedDictionary2? = False

인덱스 3에 키 "10", 값 "Ten"을 삽입하면 기존의 "4 Four" 이후 요소들이 한 칸씩 뒤로 밀리면서 삽입된 순서가 그대로 유지되는 것을 확인할 수 있습니다. 또한 두 컬렉션은 내용이 달라 Equals() 비교 결과가 False로 출력됩니다.

정리

OrderedDictionary의 Insert 메서드를 활용하면 단순히 끝에만 추가하는 Add와 달리, 원하는 위치에 정확하게 키-값 쌍을 배치할 수 있습니다. 삽입 순서가 중요한 시나리오에서 매우 유용한 기능이므로, 인덱스 범위(0부터 Count 사이)만 잘 지켜 사용하면 됩니다.