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

C#에서 OrderedDictionary의 값을 담은 ICollection 가져오는 방법


C#의 OrderedDictionary는 키-값 쌍을 삽입된 순서 그대로 유지하는 컬렉션입니다. 여기에 저장된 모든 값을 ICollection 형태로 가져오려면 Values 속성을 사용하면 됩니다.

Values 속성은 딕셔너리에 들어 있는 값들을 삽입 순서대로 담은 ICollection 객체를 반환합니다. 반환된 컬렉션은 CopyTo() 메서드를 통해 배열로 복사할 수 있으며, 이렇게 만든 배열을 반복문으로 순회하면 저장된 값들을 손쉽게 확인할 수 있습니다.

예제 1

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");

        ICollection col = dict.Values;
        String[] strVal = new String[dict.Count];
        col.CopyTo(strVal, 0);

        Console.WriteLine("Displaying the values...");
        for (int i = 0; i < dict.Count; i++) {
            Console.WriteLine(strVal[i]);
        }
    }
}

실행 결과

위 프로그램을 실행하면 다음과 같은 출력이 나타납니다.

Displaying the values...
One
Two
Three
Four
Five
Six
Seven
Eight

예제 2

이번에는 키와 값에 서로 다른 문자열을 사용하는 또 다른 예제를 살펴보겠습니다. 마찬가지로 Values 속성으로 값 컬렉션을 가져온 뒤, 배열로 복사하여 순서대로 출력합니다.

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

public class Demo {
    public static void Main() {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("One", "John");
        dict.Add("Two", "Tim");
        dict.Add("Three", "Katie");
        dict.Add("Four", "Andy");
        dict.Add("Five", "Gary");
        dict.Add("Six", "Amy");

        ICollection col = dict.Values;
        String[] strVal = new String[dict.Count];
        col.CopyTo(strVal, 0);

        Console.WriteLine("Displaying the Values...");
        for (int i = 0; i < dict.Count; i++) {
            Console.WriteLine(strVal[i]);
        }
    }
}

실행 결과

프로그램을 실행하면 아래와 같이 값들이 삽입된 순서대로 출력됩니다.

Displaying the Values...
John
Tim
Katie
Andy
Gary
Amy

정리

OrderedDictionary의 Values 속성은 저장된 모든 값을 삽입 순서대로 담은 ICollection을 반환합니다. 이 컬렉션을 CopyTo() 메서드로 배열에 복사하면 인덱스 기반 반복문으로 값을 편리하게 조회하고 처리할 수 있습니다.