C#에서 SortedList 개체에 저장된 값들의 목록을 가져오려면 GetValueList() 메서드를 사용하면 됩니다. 이 메서드는 SortedList의 모든 값을 IList 형태로 반환하며, 키를 기준으로 정렬된 순서에 따라 값들이 포함됩니다.
예제 1: 정수형 값 다루기
다음은 SortedList 개체의 값 목록을 가져오는 코드 예제입니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list = new SortedList();
list.Add("A", 1);
list.Add("B", 2);
list.Add("C", 3);
list.Add("D", 4);
list.Add("E", 5);
list.Add("F", 6);
list.Add("G", 7);
list.Add("H", 8);
Console.WriteLine("SortedList elements...");
foreach(DictionaryEntry d in list) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nList of values...SortedList");
IList col = list.GetValueList();
foreach(int res in col)
Console.WriteLine(res);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
SortedList elements... A 1 B 2 C 3 D 4 E 5 F 6 G 7 H 8 List of values...SortedList 1 2 3 4 5 6 7 8
예제 2: 문자열 값 다루기
이번에는 문자열 값을 저장한 SortedList에서 값 목록을 가져오는 또 다른 예제를 살펴보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list = new SortedList();
list.Add("One", "IT");
list.Add("Two", "Operations");
list.Add("Three", "Marketing");
list.Add("Four", "Purchase");
list.Add("Five", "Sales");
list.Add("Six", "Finance");
Console.WriteLine("SortedList elements...");
foreach(DictionaryEntry d in list) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nList of values...SortedList");
IList col = list.GetValueList();
foreach(string res in col)
Console.WriteLine(res);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
SortedList elements... Five Sales Four Purchase One IT Six Finance Three Marketing Two Operations List of values...SortedList Sales Purchase IT Finance Marketing Operations
핵심 포인트
GetValueList()는 SortedList의 모든 값을 IList 인터페이스 형태로 반환합니다.- 반환되는 값 목록은 키를 기준으로 정렬된 순서를 따릅니다.
- 키 목록이 필요한 경우에는
GetKeyList()메서드를 사용할 수 있습니다. - DictionaryEntry를 활용하면 키와 값을 함께 순회할 수 있습니다.