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

C# ListDictionary에 포함된 키/값 쌍의 개수 구하기


C#의 ListDictionary는 키/값 쌍을 연결 리스트 구조로 저장하는 특수 컬렉션으로, System.Collections.Specialized 네임스페이스에 정의되어 있습니다. ListDictionary에 포함된 키/값 쌍의 개수를 확인하려면 Count 속성을 사용하면 됩니다.

ListDictionary.Count 속성이란?

Count 속성은 ListDictionary에 실제로 저장된 키/값 쌍의 총 개수를 반환합니다. ListDictionary는 내부적으로 단일 연결 리스트로 구현되어 있어, 항목 수가 적은 경우(일반적으로 10개 미만) 해시테이블 기반 컬렉션보다 더 나은 성능을 제공합니다.

예제 1

아래 예제에서는 두 개의 ListDictionary를 생성하고, 참조를 공유하는 세 번째 딕셔너리를 Clear() 메서드로 비운 후 각각의 Count 값을 확인합니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      ListDictionary dict1 = new ListDictionary();
      dict1.Add("A", "Books");
      dict1.Add("B", "Electronics");
      dict1.Add("C", "Smart Wearables");
      dict1.Add("D", "Pet Supplies");
      dict1.Add("E", "Clothing");
      dict1.Add("F", "Footwear");
      Console.WriteLine("ListDictionary1 elements...");
      foreach(DictionaryEntry d in dict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      ListDictionary dict2 = new ListDictionary();
      dict2.Add("1", "One");
      dict2.Add("2", "Two");
      dict2.Add("3", "Three");
      dict2.Add("4", "Four");
      dict2.Add("5", "Five");
      dict2.Add("6", "Six");
      Console.WriteLine("\nListDictionary2 elements...");
      foreach(DictionaryEntry d in dict2){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of key/value pairs in Dictionary 2 = "+dict2.Count);
      ListDictionary dict3 = new ListDictionary();
      dict3 = dict2;
      Console.WriteLine("\nIs ListDictionary3 equal to ListDictionary2? = "+(dict3.Equals(dict2)));
      dict3.Clear();
      Console.WriteLine("Count of key/value pairs in Dictionary 3 = "+dict3.Count);
   }
}

출력

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

ListDictionary1 elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear

ListDictionary2 elements...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Count of key/value pairs in Dictionary 2 = 6

Is ListDictionary3 equal to ListDictionary2? = True
Count of key/value pairs in Dictionary 3 = 0

코드 설명

dict2를 dict3에 대입하면 두 변수가 동일한 객체를 참조하게 됩니다. 따라서 Equals() 비교 결과는 True이며, dict3.Clear()를 호출하면 실제로는 같은 객체를 비우는 것이므로 dict2의 내용도 함께 삭제됩니다. 그 결과 마지막 Count 값이 0으로 출력되는 것입니다. 참조형 컬렉션을 다룰 때는 이러한 참조 공유 동작을 반드시 유의해야 합니다.

예제 2

이번에는 IDictionaryEnumerator를 사용해 ListDictionary의 모든 키/값 쌍을 순회하면서 출력하고, Count 속성으로 전체 개수를 확인해 보겠습니다.

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      ListDictionary dict1 = new ListDictionary();
      dict1.Add("A", "Books");
      dict1.Add("B", "Electronics");
      dict1.Add("C", "Smart Wearables");
      dict1.Add("D", "Pet Supplies");
      dict1.Add("E", "Clothing");
      Console.WriteLine("ListDictionary1 elements...");
      foreach(DictionaryEntry d in dict1){
         Console.WriteLine(d.Key + " " + d.Value);
      }
      Console.WriteLine("Count of key/value pairs in Dictionary1 = "+dict1.Count);
      ListDictionary dict2 = new ListDictionary();
      dict2.Add("1", "One");
      dict2.Add("2", "Two");
      dict2.Add("3", "Three");
      dict2.Add("4", "Four");
      dict2.Add("5", "Five");
      dict2.Add("6", "Six");
      Console.WriteLine("\nListDictionary2 key-value pairs...");
      IDictionaryEnumerator demoEnum = dict2.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = "+ demoEnum.Value);
      Console.WriteLine("Count of key/value pairs in Dictionary2 = "+dict2.Count);
   }
}

출력

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

ListDictionary1 elements...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
Count of key/value pairs in Dictionary1 = 5

ListDictionary2 key-value pairs...
Key = 1, Value = One
Key = 2, Value = Two
Key = 3, Value = Three
Key = 4, Value = Four
Key = 5, Value = Five
Key = 6, Value = Six
Count of key/value pairs in Dictionary2 = 6

정리

ListDictionary에 저장된 요소의 개수를 알고 싶다면 Count 속성 하나면 충분합니다. foreach 문이나 IDictionaryEnumerator로 컬렉션을 순회할 때도 Count를 함께 활용하면 현재 저장된 항목 수를 손쉽게 파악할 수 있습니다. 또한 컬렉션 객체를 다른 변수에 대입하면 참조가 공유되므로, Clear() 같은 변경 작업이 원본에도 영향을 준다는 점을 기억해 두면 좋습니다.