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

C# OrderedDictionary – 지정한 키와 값으로 새 항목 삽입하는 방법

OrderedDictionary란?

C#의 OrderedDictionarySystem.Collections.Specialized 네임스페이스에 속한 컬렉션으로, 해시 테이블의 빠른 키 조회 성능과 배열의 인덱스 기반 접근 기능을 동시에 제공하며, 요소가 추가된 순서를 그대로 유지한다는 점이 큰 특징입니다.

OrderedDictionary의 특정 위치에 새 항목을 삽입할 때는 Insert(Int32, Object, Object) 메서드를 사용합니다. 이 메서드는 다음 세 개의 매개변수를 받습니다.

  • index – 새 항목이 삽입될 위치(0부터 시작하는 인덱스)
  • key – 삽입할 항목의 키
  • value – 삽입할 항목의 값

삽입이 완료되면 해당 위치 이후의 기존 항목들은 자동으로 한 칸씩 뒤로 밀려나므로, 전체 요소의 순서는 항상 유지됩니다.

예제 1: Insert()로 특정 인덱스에 항목 삽입하기

아래 예제에서는 8개의 항목을 가진 OrderedDictionary를 만든 뒤, 인덱스 7 위치에 키 "15", 값 "Fifteen"인 새 항목을 삽입합니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      dict.Add("7", "Seven");
      dict.Add("8", "Eight");

      Console.WriteLine("현재 요소 목록...");
      IDictionaryEnumerator demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }

      // 인덱스 7 위치에 새 항목 삽입
      dict.Insert(7, "15", "Fifteen");

      Console.WriteLine("삽입 후 요소 목록...");
      demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }
   }
}

실행 결과

현재 요소 목록...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 8, Value = Eight
삽입 후 요소 목록...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Key = 7, Value = Seven
Key = 15, Value = Fifteen
Key = 8, Value = Eight

출력 결과를 보면 새 항목(Key = 15)이 정확히 인덱스 7 위치, 즉 기존 마지막 항목(Key = 8) 바로 앞에 삽입된 것을 확인할 수 있습니다.

예제 2: Add()와 Insert()를 함께 사용하기

이번에는 Add() 메서드로 항목을 차례대로 추가한 후, Insert() 메서드로 원하는 위치에 새 항목을 끼워 넣는 과정을 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("A", "Laptop");
      dict.Add("B", "Desktop");

      Console.WriteLine("현재 요소 목록...");
      IDictionaryEnumerator demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }

      dict.Add("C", "Ultrabook");
      dict.Add("D", "Alienware");

      Console.WriteLine("\n항목 추가 후 요소 목록...");
      demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }

      // 인덱스 2 위치에 새 항목 삽입
      dict.Insert(2, "K", "Speakers");

      Console.WriteLine("\n삽입 후 요소 목록...");
      demoEnum = dict.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      }
   }
}

실행 결과

현재 요소 목록...
Key = A, Value = Laptop
Key = B, Value = Desktop

항목 추가 후 요소 목록...
Key = A, Value = Laptop
Key = B, Value = Desktop
Key = C, Value = Ultrabook
Key = D, Value = Alienware

삽입 후 요소 목록...
Key = A, Value = Laptop
Key = B, Value = Desktop
Key = K, Value = Speakers
Key = C, Value = Ultrabook
Key = D, Value = Alienware

마지막 출력에서 키 "K"를 가진 항목이 인덱스 2 위치에 삽입되면서, 기존의 "C"(Ultrabook)와 "D"(Alienware) 항목이 각각 한 칸씩 뒤로 이동한 것을 볼 수 있습니다.

정리

OrderedDictionary에 새 항목을 추가하는 방법은 두 가지입니다. 컬렉션 맨 끝에 덧붙이려면 Add(key, value)를, 원하는 인덱스 위치에 끼워 넣으려면 Insert(index, key, value)를 사용하면 됩니다. Insert() 호출 시 지정한 위치 이후의 항목들은 자동으로 뒤로 밀리기 때문에, 삽입 후에도 요소들의 순서가 항상 일관되게 유지됩니다.