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

C#에서 SortedList 생성하는 방법 – 예제 코드로 쉽게 배우기

C#에서 SortedList란?

SortedList는 키(Key)와 값(Value) 쌍을 저장하는 컬렉션 클래스로, 키를 기준으로 항상 오름차순으로 자동 정렬됩니다. System.Collections 네임스페이스에 포함되어 있으며, 인덱스 또는 키를 사용해 요소에 접근할 수 있다는 점이 특징입니다.

SortedList를 생성하는 기본 코드는 다음과 같습니다.

예제 1: SortedList 생성 및 요소 순회

using System;
using System.Collections;

public class Demo {
   public static void Main(String[] args) {
      SortedList sortedList = new SortedList();
      sortedList.Add("A", "1");
      sortedList.Add("B", "2");
      sortedList.Add("C", "3");
      sortedList.Add("D", "4");
      sortedList.Add("E", "5");
      sortedList.Add("F", "6");
      sortedList.Add("G", "7");
      sortedList.Add("H", "8");
      sortedList.Add("I", "9");
      sortedList.Add("J", "10");

      Console.WriteLine("SortedList elements...");
      foreach(DictionaryEntry d in sortedList) {
         Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
      }

      Console.WriteLine("Count of SortedList key-value pairs = " + sortedList.Count);

      Console.WriteLine("\nEnumerator to iterate through the SortedList...");
      IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
   }
}

출력 결과

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

SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs = 10

Enumerator to iterate through the SortedList...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10

코드 설명

  • Add() 메서드로 키와 값을 하나씩 추가하며, 추가된 요소는 키를 기준으로 자동 정렬됩니다.
  • foreach 문과 DictionaryEntry를 사용하면 모든 키-값 쌍을 간편하게 순회할 수 있습니다.
  • Count 속성은 SortedList에 저장된 키-값 쌍의 개수를 반환합니다.
  • GetEnumerator() 메서드로 IDictionaryEnumerator를 얻은 뒤 MoveNext()를 호출하면서 요소를 하나씩 탐색할 수도 있습니다.

예제 2: IndexOfValue()로 특정 값의 인덱스 찾기

이번에는 두 개의 SortedList를 만들고, IndexOfValue() 메서드를 사용해 특정 값이 저장된 인덱스 위치를 확인해 보겠습니다.

using System;
using System.Collections;

public class Demo {
   public static void Main(String[] args) {
      SortedList list1 = new SortedList();
      list1.Add("One", 1);
      list1.Add("Two", 2);
      list1.Add("Three", 3);
      list1.Add("Four", 4);
      list1.Add("Five", 5);
      list1.Add("Six", 6);
      list1.Add("Seven", 7);
      list1.Add("Eight", 8);
      list1.Add("Nine", 9);
      list1.Add("Ten", 10);

      Console.WriteLine("SortedList1 elements...");
      foreach(DictionaryEntry d in list1) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.Write("Index at value 7 = " + list1.IndexOfValue(7));

      SortedList list2 = new SortedList();
      list2.Add("A", "Accessories");
      list2.Add("B", "Books");
      list2.Add("C", "Smart Wearable Tech");
      list2.Add("D", "Home Appliances");

      Console.WriteLine("\n\nSortedList2 elements...");
      foreach(DictionaryEntry d in list2) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.Write("Index at value Books = " + list2.IndexOfValue("Books"));
   }
}

출력 결과

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

SortedList1 elements...
Eight 8
Five 5
Four 4
Nine 9
One 1
Seven 7
Six 6
Ten 10
Three 3
Two 2
Index at value 7 = 5

SortedList2 elements...
A Accessories
B Books
C Smart Wearable Tech
D Home Appliances
Index at value Books = 1

핵심 포인트

  • SortedList1은 키(영문 단어)를 알파벳 순으로 자동 정렬하여 출력합니다. 따라서 입력 순서와 무관하게 "Eight", "Five", "Four"… 순서로 정렬됩니다.
  • IndexOfValue(7)는 값 7이 저장된 인덱스 위치인 5를 반환합니다.
  • IndexOfValue("Books")는 문자열 값 "Books"의 인덱스인 1을 반환합니다.
  • 찾으려는 값이 존재하지 않으면 -1을 반환합니다.

마무리

SortedList는 데이터를 키 기준으로 항상 정렬된 상태로 유지해야 할 때 매우 유용한 컬렉션입니다. Add(), IndexOfValue(), GetEnumerator() 등 다양한 메서드를 활용하면 정렬된 키-값 데이터를 손쉽게 추가, 검색, 순회할 수 있습니다.