본문 바로가기

.NET/C#

IDictionaryEnumerator 사용하기

IDictionaryEnumerator 는 Hashtable과같은 none generic dictionary 요소들을 열거합니다.

IDictionaryEnumerator의 소스를 들여다 보면 다음과 같습니다.
public interface IDictionaryEnumerator : IEnumerator 
	{
		IDictionary Entry { get; }
		object Key { get;}
		object Value { get; }
	}
위의 Entry는 현  dictionary entry의 Key, Value값을 갖고 Key는 현 dictionary entry의 key과 Value는 현 dictionary entry의 value값을 갖습니다.

Hashtable collection은 아시다시피 key, value한쌍으로 저장되어있는데 key를 사용함으로 Hasing을 하고 그 저장소의 위치를 얻습니다. 그럼 다음예제를 보도록하죠.

static void Main(string[] args)
        {
            Hashtable hash = new Hashtable();
            hash.Add("1월""January");
            hash.Add("2월""February");
            hash.Add("3월""March");
            hash.Add("4월""April");
            hash.Add("6월""June");
            hash.Add("7월""July");
 
            Console.WriteLine("Enumerate a Hashtable\n");
            GenerateEnumerate(hash);         
 
        }
 
        static void GenerateEnumerate(Hashtable ht)
        {
            IDictionaryEnumerator ide = ht.GetEnumerator();
            while (ide.MoveNext())
            {
                Console.WriteLine("Key: {0}  Value: {1}", 
                                    ide.Key, ide.Value);
            }
            Console.ReadLine();
        }
위의 코드에서 볼수 있듯이 ht.GetEnumerator()를 호출함으로 collection 안에 있는 element들을 접근할수 있습니다.
열거자의 위치가 첫element전에 위치됨으로 MoveNext()함수를 호출하면 바로 첫번째 element에 접근할수 있습니다.  MoveNext()함수는 더이상 읽을 element가 없을시 false를 반환합니다.  위의 while 안에서 볼수 있듯이 key와 value로써 각 element의 property에 엑세스가 가능합니다.