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

C# SortedList에서 지정된 인덱스의 키 가져오는 방법 – GetKey() 완벽 정리

C#에서 SortedList 개체의 지정된 인덱스에 해당하는 키를 가져오려면 GetKey() 메서드를 사용하면 됩니다. 이 메서드는 인덱스 값을 매개변수로 전달받아 해당 위치의 키를 반환합니다.

SortedList는 내부적으로 키를 기준으로 항상 오름차순 정렬 상태를 유지하기 때문에, 인덱스는 요소가 추가된 순서가 아니라 정렬된 순서를 기준으로 한다는 점을 기억해야 합니다. 반대로 특정 키가 몇 번째 인덱스에 위치하는지 확인하고 싶다면 IndexOfKey() 메서드를 사용할 수 있습니다.

예제 1

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 key Five = "+list1.IndexOfKey("Five"));
      Console.Write("\nKey at index 2 = "+list1.GetKey(2));
      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 key B = "+list2.IndexOfKey("B"));
   }
}

출력 결과

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

SortedList1 elements...
Eight 8
Five 5
Four 4
Nine 9
One 1
Seven 7
Six 6
Ten 10
Three 3
Two 2
Index at key Five = 1
Key at index 2 = Four
SortedList2 elements...
A Accessories
B Books
C Smart Wearable Tech
D Home Appliances
Index at key B = 1

코드 설명

첫 번째 예제에서는 문자열 키와 정수 값을 가진 SortedList를 생성합니다. 요소를 추가한 뒤 foreach 루프로 전체 항목을 출력해 보면, 추가한 순서와 무관하게 키가 알파벳순(Eight, Five, Four, Nine, One...)으로 정렬되어 있는 것을 확인할 수 있습니다.

IndexOfKey("Five")는 정렬된 목록에서 "Five"가 위치한 인덱스인 1을 반환하며, GetKey(2)는 인덱스 2에 해당하는 키 "Four"를 반환합니다. 두 번째 SortedList에서도 마찬가지로 IndexOfKey("B")가 1을 반환하는 것을 볼 수 있습니다.

예제 2

이번에는 부서 정보를 담은 SortedList를 통해 다시 살펴보겠습니다 −

using System;
using System.Collections;
public class Demo {
   public static void Main(String[] args) {
      SortedList list = new SortedList();
      list.Add("One", "Finance");
      list.Add("Two", "Marketing");
      list.Add("Three", "Sales");
      list.Add("Four", "Purchase");
      list.Add("Five", "Operations");
      list.Add("Six", "IT");
      Console.WriteLine("SortedList elements...");
      foreach(DictionaryEntry d in list) {
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("\nIndex at key One = "+list.IndexOfKey("One"));
      Console.Write("\nKey at index 5 = "+list.GetKey(5));
   }
}

출력 결과

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

SortedList elements...
Five Operations
Four Purchase
One Finance
Six IT
Three Sales
Two Marketing
Index at key One = 2
Key at index 5 = Two

두 번째 예제에서도 키가 사전순(Five, Four, One, Six, Three, Two)으로 자동 정렬됩니다. 따라서 IndexOfKey("One")의 결과는 2이며, GetKey(5)는 마지막 인덱스에 해당하는 키 "Two"를 반환합니다. 이처럼 GetKey()와 IndexOfKey()를 함께 활용하면 SortedList의 키와 인덱스를 손쉽게 상호 조회할 수 있습니다.