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

C# ListDictionary에서 키를 담은 ICollection 가져오는 방법

C#의 ListDictionary는 키-값 쌍을 단일 연결 리스트 형태로 저장하는 특수 컬렉션으로, 소규모 데이터 집합을 처리할 때 유용합니다. 이 글에서는 ListDictionary에 저장된 모든 키를 ICollection 형태로 가져오는 방법을 예제와 함께 살펴보겠습니다.

ListDictionary.Keys 속성이란?

ListDictionary 클래스의 Keys 속성은 딕셔너리에 포함된 모든 키를 담은 ICollection 객체를 반환합니다. 반환된 컬렉션은 읽기 전용이므로 직접 수정할 수 없으며, foreach 루프를 사용해 각 키를 순회하며 확인할 수 있습니다.

예제 1: 숫자형 문자열 키 사용하기

다음 예제에서는 ListDictionary에 여러 항목을 추가한 후, Keys 속성으로 키 컬렉션을 가져와 화면에 출력합니다.

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

public class Demo {
   public static void Main(){
      ListDictionary listDict = new ListDictionary();
      listDict.Add("1", "Laptop");
      listDict.Add("2", "Tablet");
      listDict.Add("3", "Desktop");
      listDict.Add("4", "Speaker");
      listDict.Add("5", "Earphone");
      listDict.Add("6", "Headphone");

      ICollection col = listDict.Keys;
      foreach(String s in col){
         Console.WriteLine(s);
      }
  }
}

출력 결과

위 코드를 실행하면 다음과 같이 저장된 모든 키가 순서대로 출력됩니다.

1
2
3
4
5
6

예제 2: 알파벳 키 사용하기

이번에는 문자형 키를 사용해 동일하게 Keys 속성을 활용하는 예제입니다.

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

public class Demo {
   public static void Main(){
      ListDictionary listDict = new ListDictionary();
      listDict.Add("A", "Tom");
      listDict.Add("B", "John");
      listDict.Add("C", "Kevin");
      listDict.Add("D", "Tim");

      ICollection col = listDict.Keys;
      foreach(String s in col){
         Console.WriteLine(s);
      }
  }
}

출력 결과

실행하면 아래와 같이 추가된 순서대로 키가 출력됩니다.

A
B
C
D

정리

ListDictionary의 Keys 속성을 활용하면 저장된 모든 키를 ICollection으로 손쉽게 가져올 수 있습니다. 참고로 값만 필요한 경우에는 Values 속성을 사용하면 되며, ListDictionary는 요소 수가 적을 때 성능이 좋으므로 대량의 데이터에는 Hashtable이나 Dictionary<TKey, TValue> 사용을 권장합니다.