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

C# SortedDictionary.Values 속성 사용법 완벽 정리

C#의 SortedDictionary.Values 속성은 SortedDictionary<TKey, TValue>에 저장된 모든 값(value)을 담고 있는 컬렉션을 반환합니다. 이 속성이 유용한 이유는 별도의 반복 처리 없이도 사전에 들어 있는 값들만 한 번에 꺼내 확인할 수 있기 때문입니다.

Values 속성이 반환하는 컬렉션은 SortedDictionary<TKey, TValue>.ValueCollection 타입으로, 키가 정렬된 순서와 동일한 순서로 값들을 열거합니다. 또한 이 컬렉션은 원본 SortedDictionary와 연동되어 있으므로, 사전에서 요소가 추가되거나 제거되면 해당 변경 사항이 그대로 반영됩니다.

구문

Values 속성의 기본 구문은 다음과 같습니다.

public System.Collections.Generic.SortedDictionary<TKey,TValue>.ValueCollection Values { get; }

getter만 제공하는 읽기 전용 속성이므로 컬렉션 자체에 직접 요소를 추가하거나 삭제할 수는 없으며, 값의 변경은 사전의 인덱서나 Add·Remove 메서드를 통해 수행해야 합니다.

예제 1

다음 예제는 SortedDictionary에 요소를 추가한 후 특정 키를 제거하고, Keys 및 Values 속성을 이용해 전체 목록을 출력하는 과정을 보여줍니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(1, "Ultrabook");
      sortedDict.Add(2, "Alienware");
      sortedDict.Add(3, "Notebook");
      sortedDict.Add(4, "Connector");
      sortedDict.Add(5, "Flash Drive");
      sortedDict.Add(6, "SSD");
      sortedDict.Add(7, "HDD");
      sortedDict.Add(8, "Earphone");

      Console.WriteLine("SortedDictionary 키-값 쌍...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);

      Console.WriteLine("\n키 7 제거 성공 여부 = " + sortedDict.Remove(7));

      Console.WriteLine("\nSortedDictionary 키-값 쌍... 업데이트됨");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);

      SortedDictionary<int, string>.KeyCollection keyList = sortedDict.Keys;
      Console.WriteLine("\n키 목록...");
      foreach(int i in keyList){
         Console.WriteLine(i);
      }

      SortedDictionary<int, string>.ValueCollection valList = sortedDict.Values;
      Console.WriteLine("\n값 목록...");
      foreach(string s in valList){
         Console.WriteLine(s);
      }
   }
}

실행 결과

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

SortedDictionary 키-값 쌍...
키 = 1, 값 = Ultrabook
키 = 2, 값 = Alienware
키 = 3, 값 = Notebook
키 = 4, 값 = Connector
키 = 5, 값 = Flash Drive
키 = 6, 값 = SSD
키 = 7, 값 = HDD
키 = 8, 값 = Earphone
키 7 제거 성공 여부 = True
SortedDictionary 키-값 쌍... 업데이트됨
키 = 1, 값 = Ultrabook
키 = 2, 값 = Alienware
키 = 3, 값 = Notebook
키 = 4, 값 = Connector
키 = 5, 값 = Flash Drive
키 = 6, 값 = SSD
키 = 8, 값 = Earphone
키 목록...
1
2
3
4
5
6
8
값 목록...
Ultrabook
Alienware
Notebook
Connector
Flash Drive
SSD
Earphone

출력 결과에서 알 수 있듯이 Remove(7) 메서드로 키 7(HDD)이 성공적으로 제거되었으며, 이후 Keys와 Values 속성을 통해 얻은 목록에는 해당 요소가 더 이상 포함되지 않습니다.

예제 2

이번에는 차량 종류를 값으로 저장하는 두 번째 예제를 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(1, "SUV");
      sortedDict.Add(2, "MUV");
      sortedDict.Add(3, "Hatchback");
      sortedDict.Add(4, "AUV");
      sortedDict.Add(5, "Convertible");
      sortedDict.Add(6, "Crossover");
      sortedDict.Add(7, "Utility Vehicle");

      Console.WriteLine("SortedDictionary 키-값 쌍...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);

      Console.WriteLine("\n키 2 제거 성공 여부 = " + sortedDict.Remove(2));

      Console.WriteLine("\nSortedDictionary 키-값 쌍... 업데이트됨");
      demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("키 = " + demoEnum.Key + ", 값 = " + demoEnum.Value);

      SortedDictionary<int, string>.KeyCollection keyList = sortedDict.Keys;
      Console.WriteLine("\n키 목록...");
      foreach(int i in keyList){
         Console.WriteLine(i);
      }

      SortedDictionary<int, string>.ValueCollection valList = sortedDict.Values;
      Console.WriteLine("\n값 목록...");
      foreach(string s in valList){
         Console.WriteLine(s);
      }
   }
}

실행 결과

SortedDictionary 키-값 쌍...
키 = 1, 값 = SUV
키 = 2, 값 = MUV
키 = 3, 값 = Hatchback
키 = 4, 값 = AUV
키 = 5, 값 = Convertible
키 = 6, 값 = Crossover
키 = 7, 값 = Utility Vehicle
키 2 제거 성공 여부 = True
SortedDictionary 키-값 쌍... 업데이트됨
키 = 1, 값 = SUV
키 = 3, 값 = Hatchback
키 = 4, 값 = AUV
키 = 5, 값 = Convertible
키 = 6, 값 = Crossover
키 = 7, 값 = Utility Vehicle
키 목록...
1
3
4
5
6
7
값 목록...
SUV
Hatchback
AUV
Convertible
Crossover
Utility Vehicle

정리

  • Values 속성은 SortedDictionary의 모든 값을 ValueCollection 형태로 반환합니다.
  • 반환된 컬렉션은 키의 정렬 순서를 그대로 따르므로, 값들이 항상 일관된 순서로 열거됩니다.
  • foreach 문을 활용하면 값 목록을 간결하게 순회할 수 있으며, Keys 속성과 함께 사용하면 키와 값을 각각 따로 처리하기에도 편리합니다.