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

C# ListDictionary의 값을 ICollection으로 가져오는 방법

C# ListDictionary의 값을 ICollection으로 가져오기

C#에서 ListDictionary에 저장된 모든 값을 ICollection 형태로 가져오려면 Values 속성을 사용하면 됩니다. 이 속성은 딕셔너리의 키(key)가 아닌 값(value)들만 모아 컬렉션으로 반환해 주며, foreach 문을 사용해 각 요소를 쉽게 순회할 수 있습니다.

참고로 ListDictionary는 단일 연결 리스트 기반으로 구현된 소규모 컬렉션용 클래스로, 일반적으로 항목 수가 10개 미만일 때 가장 좋은 성능을 발휘합니다.

예제 1

다음은 ListDictionary에 여러 항목을 추가한 후, Values 속성으로 값 컬렉션을 가져와 출력하는 예제입니다.

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.Values;
      foreach(String s in col){
         Console.WriteLine(s);
      }
  }
}

출력 결과

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

Laptop
Tablet
Desktop
Speaker
Earphone
Headphone

예제 2

이번에는 문자열 키를 사용하는 또 다른 예제를 살펴보겠습니다. 동작 방식은 동일하며, 숫자 키 대신 문자 키를 사용했을 뿐입니다.

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.Values;
      foreach(String s in col){
         Console.WriteLine(s);
      }
  }
}

출력 결과

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

Tom
John
Kevin
Tim

정리

ListDictionary에서 값만 추출하고 싶다면 Values 속성을 호출하여 ICollection 객체를 얻으면 됩니다. 반대로 키 목록이 필요하다면 Keys 속성을 사용하면 되며, 키와 값을 함께 확인하려면 IDictionaryEnumerator를 활용할 수도 있습니다.