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

C#에서 ListDictionary를 만드는 방법 – 생성부터 활용까지

ListDictionarySystem.Collections.Specialized 네임스페이스에 속한 컬렉션 클래스로, 키(key)와 값(value) 쌍을 단일 연결 리스트(singly linked list) 구조로 저장합니다. 저장되는 항목이 10개 이하인 소규모 데이터 집합을 처리할 때 가장 효율적으로 동작하도록 설계되었습니다.

ListDictionary 객체를 생성하려면 먼저 해당 네임스페이스를 using 문으로 가져온 뒤, new 키워드로 인스턴스를 만들고 Add() 메서드를 사용해 키와 값을 추가하면 됩니다.

예제 1: ListDictionary 생성 및 요소 추가

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

public class Demo {
   public static void Main(){
      ListDictionary dict = new ListDictionary();
      dict.Add("1", "SUV");
      dict.Add("2", "Sedan");
      dict.Add("3", "Utility Vehicle");
      dict.Add("4", "Compact Car");
      dict.Add("5", "SUV");
      dict.Add("6", "Sedan");
      dict.Add("7", "Utility Vehicle");
      dict.Add("8", "Compact Car");
      dict.Add("9", "Crossover");
      dict.Add("10", "Electric Car");

      Console.WriteLine("ListDictionary elements...");
      foreach(DictionaryEntry d in dict){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      Console.WriteLine("\nIs the ListDictionary having fixed size? = "+dict.IsFixedSize);
      Console.WriteLine("If ListDictionary read-only? = "+dict.IsReadOnly);
      Console.WriteLine("Is ListDictionary synchronized = "+dict.IsSynchronized);
      Console.WriteLine("The ListDictionary has the key K? = "+dict.Contains("K"));
      Console.WriteLine("The ListDictionary has the key 9? = "+dict.Contains("9"));
   }
}

출력 결과

ListDictionary elements...
1 SUV
2 Sedan
3 Utility Vehicle
4 Compact Car
5 SUV
6 Sedan
7 Utility Vehicle
8 Compact Car
9 Crossover
10 Electric Car
Is the ListDictionary having fixed size? = False
If ListDictionary read-only? = False
Is ListDictionary synchronized = False
The ListDictionary has the key K? = False
The ListDictionary has the key 9? = True

주요 속성 및 메서드 설명

  • IsFixedSize: ListDictionary가 고정 크기를 갖는지 여부를 반환합니다. 이 예제에서는 False로, 크기가 고정되어 있지 않음을 의미합니다.
  • IsReadOnly: 읽기 전용 여부를 나타냅니다. False이므로 요소를 자유롭게 추가하거나 수정할 수 있습니다.
  • IsSynchronized: 스레드 동기화 여부를 반환합니다. 기본값은 False이며, 멀티스레드 환경에서는 별도의 동기화 처리가 필요합니다.
  • Contains(): 지정한 키가 ListDictionary에 존재하는지 확인합니다. 위 예제에서 키 "K"는 존재하지 않아 False, 키 "9"는 존재하여 True가 반환되었습니다.

예제 2: 두 개의 ListDictionary 비교 및 초기화

이번에는 서로 다른 두 개의 ListDictionary를 생성하고, 참조 할당과 Equals() 비교, 그리고 Clear() 메서드를 통한 전체 삭제 과정을 살펴보겠습니다.

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

public class Demo {
   public static void Main(){
      ListDictionary dict1 = new ListDictionary();
      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("ListDictionary1 elements...");
      foreach(DictionaryEntry d in dict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      ListDictionary dict2 = new ListDictionary();
      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("\nListDictionary2 elements...");
      foreach(DictionaryEntry d in dict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }

      Console.WriteLine("Count of key/value pairs in Dictionary 2 = "+dict2.Count);

      ListDictionary dict3 = new ListDictionary();
      dict3 = dict2;
      Console.WriteLine("\nIs ListDictionary3 equal to ListDictionary2? = "+(dict3.Equals(dict2)));

      dict3.Clear();
      Console.WriteLine("Count of key/value pairs in Dictionary 3 = "+dict3.Count);
   }
}

출력 결과

ListDictionary1 elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
ListDictionary2 elements...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Count of key/value pairs in Dictionary 2 = 6
Is ListDictionary3 equal to ListDictionary2? = True
Count of key/value pairs in Dictionary 3 = 0

코드 해설

  • Count 속성: ListDictionary에 저장된 키/값 쌍의 개수를 반환합니다. dict2에는 6개의 항목이 있으므로 6이 출력됩니다.
  • Equals() 메서드: dict3에 dict2를 대입하면 두 변수가 동일한 객체를 참조하게 되므로 Equals 비교 결과는 True입니다.
  • Clear() 메서드: ListDictionary의 모든 요소를 제거합니다. dict3.Clear() 호출 후 Count가 0이 된 것은 dict3와 dict2가 같은 객체를 가리키기 때문에, 사실상 dict2의 내용까지 모두 비워진 것과 같습니다.

이처럼 ListDictionary는 소규모 키/값 데이터를 순서대로 관리할 때 유용한 컬렉션입니다. 다만 항목 수가 많아지면 성능이 저하될 수 있으므로, 대용량 데이터를 다룰 때는 Hashtable이나 Dictionary<TKey, TValue>를 사용하는 것이 좋습니다.