C#: Using IDictionaryEnumerator with HashTable

Posted by: Suprotim Agarwal , on 8/8/2011, in Category C#
Views: 72297
Abstract: In this article, we will see how to enumerate a HashTable using an IDictionaryEnumerator.

The IDictionaryEnumerator enumerates the elements of a non-generic dictionary like a HashTable. It is a strongly typed enumerator which inherits IEnumerator by adding three properties:

IDictionaryEnumerator

where Entry gets both the key and the value of the current dictionary entry in the form of a DictionaryEntry struct, Key gets the key of the current dictionary entry and Value gets the value of the current dictionary entry.

A HashTable collection stores a (Key, Value) pair and uses the Key to hash and obtain the storage location. Let us see how to enumerate a HashTable using an IDictionaryEnumerator

idictionary-enumerator-loop

 

As you can see in the code above, we are using HashTable.GetEnumerator which iterates through the HashTable. Since the the enumerator is positioned before the first element in the collection, you must call the MoveNext method to advance the enumerator to the first element of the collection. When there are no more elements to read, MoveNext() returns false. The current value is obtained using Entry, Key and Value.

Note: You can also access items in the Dictionary using the generalized Entry property which returns a DictionaryEntry class type i.e. via ide.Entry.Key and ide.Entry.Value

OUTPUT

image

While Enumerating a HashTable or a non-generic dictionary key value pair, use the IDictionaryEnumerator instead of the IEnumerator since the former gives you access to both the key and value of the current entry.

I hope this article was useful and I thank you for viewing it.

The entire source code of this article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Santhosh on Thursday, October 20, 2011 10:26 AM
It was good. Thanks.
Comment posted by Iyyappam on Monday, November 26, 2012 9:05 AM
Easy to understand the concept of IDictionaryEnumerator and Hash table.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel